// Standort & Öffnungszeiten

const AZRA_LAT = 50.1402957;
const AZRA_LNG = 8.1562216;
const LEAFLET_CSS = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css';
const LEAFLET_JS  = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js';

function loadStylesheet(href) {
  return new Promise((resolve, reject) => {
    if (document.querySelector(`link[data-azra-css="${href}"]`)) return resolve();
    const link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = href;
    link.setAttribute('data-azra-css', href);
    link.onload = () => resolve();
    link.onerror = () => reject(new Error('css load failed: ' + href));
    document.head.appendChild(link);
  });
}
function loadScript(src) {
  return new Promise((resolve, reject) => {
    if (window.L) return resolve();
    if (document.querySelector(`script[data-azra-js="${src}"]`)) {
      const t = setInterval(() => { if (window.L) { clearInterval(t); resolve(); } }, 40);
      return;
    }
    const s = document.createElement('script');
    s.src = src;
    s.async = true;
    s.setAttribute('data-azra-js', src);
    s.onload = () => resolve();
    s.onerror = () => reject(new Error('script load failed: ' + src));
    document.head.appendChild(s);
  });
}

function MapEmbed({ label, addrShort }) {
  const containerRef = React.useRef(null);
  const mapRef = React.useRef(null);
  React.useEffect(() => {
    const el = containerRef.current;
    if (!el) return;
    let cancelled = false;
    const init = async () => {
      try {
        await Promise.all([loadStylesheet(LEAFLET_CSS), loadScript(LEAFLET_JS)]);
        if (cancelled || !window.L || mapRef.current) return;
        const L = window.L;
        const map = L.map(el, {
          scrollWheelZoom: false,
          zoomControl: true,
          attributionControl: true,
        }).setView([AZRA_LAT, AZRA_LNG], 16);
        L.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png', {
          attribution: '&copy; <a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener">OpenStreetMap</a> &middot; &copy; <a href="https://carto.com/attributions" target="_blank" rel="noopener">CARTO</a>',
          subdomains: 'abcd',
          maxZoom: 19,
        }).addTo(map);
        const pinSvg =
          '<svg viewBox="0 0 24 32" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">'
          + '<path d="M12 31C12 31 21 18 21 11.5C21 6 17 2 12 2C7 2 3 6 3 11.5C3 18 12 31 12 31Z" fill="#7A2E1F" stroke="#FAF6EA" stroke-width="2"/>'
          + '<circle cx="12" cy="11.5" r="3.6" fill="#FAF6EA"/>'
          + '</svg>';
        const icon = L.divIcon({
          className: 'azra-pin',
          html: pinSvg,
          iconSize: [36, 48],
          iconAnchor: [18, 46],
          popupAnchor: [0, -42],
        });
        const marker = L.marker([AZRA_LAT, AZRA_LNG], { icon, title: label, alt: label, keyboard: false })
          .addTo(map)
          .bindPopup(
            '<strong style="font-family:var(--font-display);font-size:15px">'
            + (label || 'Azra Markt')
            + '</strong><br/><span style="font-family:var(--font-mono);font-size:11px;letter-spacing:.04em">'
            + (addrShort || 'Gottfried-Keller-Str. 4, 65232 Taunusstein')
            + '</span>',
            { closeButton: true, autoClose: false, closeOnClick: false, autoPan: false }
          );
        // Auf Desktop Popup direkt anzeigen, auf Mobile nur per Tap (zu wenig Platz)
        const isWide = typeof window !== 'undefined' && window.matchMedia && window.matchMedia('(min-width: 600px)').matches;
        if (isWide) marker.openPopup();
        mapRef.current = map;
        el.dataset.loaded = 'true';
        // Tile-layout fix after late mount (e.g. after lazy load)
        setTimeout(() => { if (mapRef.current) mapRef.current.invalidateSize(); }, 120);
      } catch (e) {
        console.error('[map] load failed', e);
      }
    };
    const io = new IntersectionObserver((entries) => {
      if (entries.some(e => e.isIntersecting)) {
        io.disconnect();
        init();
      }
    }, { rootMargin: '300px' });
    io.observe(el);
    return () => {
      cancelled = true;
      io.disconnect();
      if (mapRef.current) {
        try { mapRef.current.remove(); } catch (e) {}
        mapRef.current = null;
      }
    };
  }, [label, addrShort]);
  return <div ref={containerRef} className="map-leaflet" role="img" aria-label={label}/>;
}

function Standort() {
  const { t } = useT();
  const status = useOpenStatus();
  const todayIdx = (new Date().getDay() + 6) % 7;
  const days = t('hours.days') || [];

  const headline = t('standort.headline');
  const headlineEm = t('standort.headlineEm');
  const idx = headline.indexOf(headlineEm);
  const before = idx >= 0 ? headline.slice(0, idx) : headline;
  const after  = idx >= 0 ? headline.slice(idx + headlineEm.length) : '';

  return (
    <section id="standort" style={{ background:'var(--bg-2)' }}>
      <div className="container">
        <div className="st-grid">
          <div>
            <span className="eyebrow">{t('standort.eyebrow')}</span>
            <h2 style={{ marginTop:8 }}>{before}<span className="hand" style={{ color:'var(--brick)', fontSize:'1.15em', display:'inline-block', transform:'rotate(-2deg)' }}>{headlineEm}</span>{after}</h2>
            <div className="map-wrap keep-ltr">
              <MapEmbed label={t('site.name')} addrShort="Gottfried-Keller-Str. 4, 65232 Taunusstein"/>
              <div className="map-route-overlay">
                <a href="https://maps.google.com/?q=Gottfried-Keller-Stra%C3%9Fe+4+65232+Taunusstein" target="_blank" rel="noopener" className="btn" style={{ padding:'10px 16px', fontSize:13 }}>
                  <Icon name="route" size={14}/> {t('common.planRoute')}
                </a>
              </div>
            </div>
            <div style={{ marginTop:18, display:'flex', gap:24, flexWrap:'wrap', fontSize:14, color:'var(--ink-2)' }}>
              <span style={{ display:'flex', alignItems:'center', gap:8 }}><Icon name="pin" size={14}/> {t('site.address')}, {t('site.city')}</span>
              <span style={{ display:'flex', alignItems:'center', gap:8 }}><Icon name="phone" size={14}/> <span className="ltr">{t('site.phoneHuman')}</span></span>
            </div>
          </div>

          <div className="st-card">
            <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:18 }}>
              <span className={`live-dot ${status.open?'':'closed'}`}></span>
              <span style={{ fontFamily:'var(--font-display)', fontSize:22, fontWeight:600 }}>{status.open ? t('common.openNow') : t('common.closedNow')}</span>
            </div>
            <div style={{ color:'var(--ink-2)', fontSize:14 }}>{status.label}</div>
            <div className="rule" style={{ margin:'22px 0' }}></div>
            <div className="eyebrow" style={{ marginBottom:14 }}>{t('standort.hours')}</div>
            <ul style={{ margin:0, padding:0, listStyle:'none', display:'grid', gap:6 }}>
              {HOURS.map((h,i)=>(
                <li key={i} style={{ display:'flex', justifyContent:'space-between', padding:'8px 0', borderBottom:'1px solid var(--line)',
                  fontWeight: i===todayIdx?600:400, color: i===todayIdx?'var(--ink)':'var(--ink-2)' }}>
                  <span>{days[i]}{i===todayIdx && <span style={{ marginInlineStart:8, fontSize:11, color:'var(--brick)', fontFamily:'var(--font-mono)', letterSpacing:'.06em' }}>{t('standort.today')}</span>}</span>
                  <span className="ltr" style={{ fontVariantNumeric:'tabular-nums' }}>{h.o ? `${h.o} – ${h.c}` : t('common.closed')}</span>
                </li>
              ))}
            </ul>
            <div style={{ marginTop:22, display:'flex', gap:10 }}>
              <a href="tel:+4917624846057" className="btn" style={{ flex:1, justifyContent:'center', padding:'12px 16px', fontSize:13 }}><Icon name="phone" size={14}/> {t('common.call')}</a>
              <a href="https://maps.google.com/?q=Gottfried-Keller-Stra%C3%9Fe+4+65232+Taunusstein" target="_blank" rel="noopener" className="btn ghost" style={{ flex:1, justifyContent:'center', padding:'12px 16px', fontSize:13 }}><Icon name="route" size={14}/> {t('common.route')}</a>
            </div>
          </div>
        </div>
      </div>
      <style>{`
        .st-grid{ display:grid; grid-template-columns:1fr; gap:24px; align-items:flex-start; }
        .st-card{ background:var(--paper); border:1px solid var(--line); border-radius:8px; padding:22px 20px; }
        #standort .map-wrap{ margin-top:20px; }
        .map-leaflet{ position:absolute; inset:0; width:100%; height:100%; background:var(--bg-2); }
        .map-leaflet .leaflet-tile-pane{ filter:saturate(.92); }
        .azra-pin{ background:transparent !important; border:0 !important; }
        .azra-pin svg{ width:36px; height:48px; display:block; filter:drop-shadow(0 4px 10px rgba(42,27,18,.35)); }
        .leaflet-popup-content-wrapper{ background:var(--paper) !important; color:var(--ink) !important;
          border:1px solid var(--line); border-radius:6px !important; box-shadow:0 12px 30px rgba(0,0,0,.18); }
        .leaflet-popup-content{ margin:10px 14px !important; line-height:1.35 !important; }
        .leaflet-popup-tip{ background:var(--paper) !important; }
        .leaflet-container a.leaflet-popup-close-button{ color:var(--ink-2) !important; }
        .leaflet-control-attribution{ background:rgba(250,246,234,.85) !important; font-size:10px !important; }
        .leaflet-control-attribution a{ color:var(--brick) !important; }
        .map-route-overlay{ position:absolute; bottom:14px; right:14px; display:none; gap:8px; z-index:500; }
        @media (min-width: 600px){
          .st-grid{ gap:32px; }
          .st-card{ padding:24px 26px; }
          #standort .map-wrap{ margin-top:24px; }
        }
        @media (min-width: 900px){
          .st-grid{ grid-template-columns:1.1fr .9fr; gap:48px; }
          .st-card{ padding:28px 30px; }
          #standort .map-wrap{ margin-top:28px; }
          .map-route-overlay{ display:flex; }
        }
      `}</style>
    </section>
  );
}
window.Standort = Standort;
