// Tours (trails) page — trails from Supabase, GPX rendered on a Leaflet map
const { useState: useStateT, useEffect: useEffectT, useRef: useRefT } = React;

function TrailMap({ trails, focus }) {
  const mapRef = useRefT(null);
  const mapObj = useRefT(null);
  const layersRef = useRefT({});

  useEffectT(() => {
    if (!mapRef.current || mapObj.current) return;
    const map = L.map(mapRef.current, { scrollWheelZoom: false });
    map.setView([45.36, 23.23], 12); // Lupeni / Straja
    L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', {
      attribution: '&copy; OpenStreetMap &copy; CARTO',
      maxZoom: 19,
    }).addTo(map);
    mapObj.current = map;
  }, []);

  useEffectT(() => {
    const map = mapObj.current;
    if (!map) return;
    Object.values(layersRef.current).forEach(l => map.removeLayer(l));
    layersRef.current = {};
    const withGpx = trails.filter(tr => tr.gpx_path);
    if (withGpx.length === 0) return;
    const bounds = [];
    withGpx.forEach(tr => {
      const layer = new L.GPX(db.gpxPublicUrl(tr.gpx_path), {
        async: true,
        marker_options: { startIconUrl: null, endIconUrl: null, shadowUrl: null },
        polyline_options: { color: '#dc2626', weight: 3, opacity: 0.9 },
      });
      layer.on('loaded', e => {
        bounds.push(e.target.getBounds());
        map.fitBounds(bounds.reduce((a, b) => a.extend(b)), { padding: [30, 30] });
      });
      layer.bindPopup(() => `<b>${tr.name}</b>${tr.distance_km ? ' · ' + tr.distance_km + ' km' : ''}`);
      layer.addTo(map);
      layersRef.current[tr.id] = layer;
    });
  }, [trails]);

  useEffectT(() => {
    const map = mapObj.current;
    if (!map || !focus) return;
    const layer = layersRef.current[focus];
    if (layer && layer.getBounds && layer.getBounds().isValid()) {
      map.fitBounds(layer.getBounds(), { padding: [30, 30] });
    }
  }, [focus]);

  return <div ref={mapRef} style={{ position: 'absolute', inset: 0, background: '#050505' }}></div>;
}

function PageTours({ lang }) {
  const t = window.CONTENT[lang].tours;
  const [filter, setFilter] = useStateT('ALL');
  const [focus, setFocus] = useStateT(null);
  const trails = useFetch(db.fetchTrails);
  const all = trails.data || [];
  const filtered = all.filter(tr => filter === 'ALL' || tr.difficulty === filter);
  const hasGpx = all.some(tr => tr.gpx_path);

  return (
    <div>
      <section style={{ padding: '80px 0 60px', borderBottom: '1px solid var(--border)' }}>
        <div className="container">
          <div className="eyebrow" style={{ marginBottom: 28 }}>{t.eyebrow}</div>
          <h1 className="display display-xxl" style={{ marginBottom: 40 }}>
            <div>{t.title_1}</div>
            <div style={{ color: 'var(--accent)' }}>{t.title_2}</div>
          </h1>
          <p style={{ fontSize: 20, maxWidth: 680, color: 'var(--fg-dim)', lineHeight: 1.55 }}>{t.sub}</p>
        </div>
      </section>

      {trails.loading ? null : all.length === 0 ? (
        <section className="section">
          <div className="container">
            <ComingSoon note={t.coming_note} label="GARMIN · GPX · VALEA JIULUI" />
          </div>
        </section>
      ) : (
        <>
          {/* Filters + legend */}
          <section style={{ padding: '40px 0', borderBottom: '1px solid var(--border)', background: 'rgba(10,10,10,0.95)', zIndex: 20 }}>
            <div className="container" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 24 }}>
              <div style={{ display: 'flex', gap: 6 }}>
                {['ALL', 'EASY', 'MID', 'HARD'].map(f => (
                  <button key={f}
                    onClick={() => setFilter(f)}
                    style={{
                      padding: '10px 18px',
                      fontFamily: 'JetBrains Mono, monospace', fontSize: 12, fontWeight: 700, letterSpacing: '0.12em',
                      background: filter === f ? 'var(--accent)' : 'var(--bg-2)',
                      color: filter === f ? '#fff' : 'var(--fg-dim)',
                      border: '1px solid ' + (filter === f ? 'var(--accent)' : 'var(--border)'),
                      transition: 'all 160ms',
                    }}>
                    {f === 'ALL' ? t.filter_all : f}
                  </button>
                ))}
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 24, flexWrap: 'wrap' }}>
                <span className="mono" style={{ fontSize: 11, color: 'var(--fg-dim)', letterSpacing: '0.18em' }}>{t.filter_legend}:</span>
                {t.legend.map((l, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <DiffBadge d={l.c} />
                    <span style={{ fontSize: 13, color: 'var(--fg-dim)' }}>{l.d}</span>
                  </div>
                ))}
              </div>
            </div>
          </section>

          {/* Interactive map */}
          {hasGpx && (
            <section style={{ padding: '60px 0', background: 'var(--bg-2)' }}>
              <div className="container">
                <div className="eyebrow" style={{ marginBottom: 20 }}>/ {t.map_title.toLowerCase()}</div>
                <div style={{ position: 'relative', height: 520, border: '1px solid var(--border)', overflow: 'hidden' }}>
                  <TrailMap trails={all} focus={focus} />
                </div>
              </div>
            </section>
          )}

          {/* List */}
          <section className="section">
            <div className="container">
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 40 }}>
                <h2 className="display display-md">{t.list_title}</h2>
                <div className="mono" style={{ fontSize: 12, color: 'var(--fg-dim)', letterSpacing: '0.12em' }}>
                  [ {filtered.length} / {all.length} ]
                </div>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 1, background: 'var(--border)' }}>
                {filtered.map((tr, i) => (
                  <div key={tr.id} className="trail-row" style={{
                    display: 'grid', gridTemplateColumns: '60px 1fr 140px 120px 100px 100px 160px',
                    gap: 24, alignItems: 'center', padding: '22px 28px',
                    background: 'var(--bg)', transition: 'all 180ms',
                  }}
                  onMouseEnter={e => { e.currentTarget.style.background = 'var(--bg-3)'; }}
                  onMouseLeave={e => { e.currentTarget.style.background = 'var(--bg)'; }}>
                    <div className="mono" style={{ fontSize: 14, color: 'var(--fg-dimmer)', fontWeight: 700 }}>#{String(i + 1).padStart(2, '0')}</div>
                    <div>
                      <h3 style={{ fontFamily: 'Barlow Condensed', fontStyle: 'italic', fontWeight: 900, fontSize: 24, textTransform: 'uppercase', marginBottom: 4 }}>{tr.name}</h3>
                      <div className="mono" style={{ fontSize: 11, color: 'var(--fg-dim)', letterSpacing: '0.12em' }}>
                        {[tr.zone && tr.zone.toUpperCase(), tr.description].filter(Boolean).join(' · ')}
                      </div>
                    </div>
                    <div>
                      <div className="mono" style={{ fontSize: 10, color: 'var(--fg-dimmer)', letterSpacing: '0.15em', marginBottom: 2 }}>DISTANȚĂ</div>
                      <div style={{ fontFamily: 'Barlow Condensed', fontWeight: 700, fontSize: 22 }}>{tr.distance_km || '—'} <span style={{ fontSize: 12, color: 'var(--fg-dim)' }}>KM</span></div>
                    </div>
                    <div>
                      <div className="mono" style={{ fontSize: 10, color: 'var(--fg-dimmer)', letterSpacing: '0.15em', marginBottom: 2 }}>URCARE</div>
                      <div style={{ fontFamily: 'Barlow Condensed', fontWeight: 700, fontSize: 22 }}>{tr.elevation_m || '—'} <span style={{ fontSize: 12, color: 'var(--fg-dim)' }}>M↑</span></div>
                    </div>
                    <div>
                      <div className="mono" style={{ fontSize: 10, color: 'var(--fg-dimmer)', letterSpacing: '0.15em', marginBottom: 2 }}>TIMP</div>
                      <div style={{ fontFamily: 'Barlow Condensed', fontWeight: 700, fontSize: 22 }}>{tr.duration || '—'}</div>
                    </div>
                    <div>{tr.difficulty && <DiffBadge d={tr.difficulty} />}</div>
                    <div>
                      {tr.gpx_path && (
                        <button className="btn btn-ghost" style={{ padding: '10px 16px', fontSize: 13 }}
                          onClick={() => { setFocus(null); setTimeout(() => setFocus(tr.id), 0); document.querySelector('.leaflet-container') && document.querySelector('.leaflet-container').scrollIntoView({ behavior: 'smooth', block: 'center' }); }}>
                          {t.cta} →
                        </button>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </section>
        </>
      )}
    </div>
  );
}
window.PageTours = PageTours;
