/* OnSumn v2 — Glass Event Cards + Grid */

/* Hardcoded fallback events — used when events.json hasn't been generated yet */
const FALLBACK_EVENTS = [
  { id: 1, tag: 'THE TOWN', city: 'OAKLAND', title: 'Sideshow Art Gallery — First Friday', desc: 'Pull up for the vibes, the art, and the community. Oakland\'s finest on display.', date: 'Apr 25', time: '6 PM', venue: 'Telegraph Ave', category: 'ART', lat: 37.8116, lng: -122.2686 },
  { id: 2, tag: 'SAN JOSE', city: 'SAN JOSE', title: 'TCG & Sports Card Expo — SJ', desc: 'Pokémon, Yu-Gi-Oh, One Piece, sports cards — vendors and graded slabs under one roof.', date: 'Apr 26', time: '10 AM', venue: 'San Jose Convention Center', category: 'CULTURE', lat: 37.3302, lng: -121.8880 },
  { id: 3, tag: 'SF MISSION', city: 'SF', title: 'Hyphy Renaissance: 00s Party', desc: 'Going dumb with the classics. Thizzelle era all night. Bay vibes forever.', date: 'Apr 26', time: '9 PM', venue: 'The Knockout', category: 'NIGHTLIFE', lat: 37.7455, lng: -122.4214 },
  { id: 4, tag: 'VALLEJO', city: 'VALLEJO', title: 'Bay Area Noodle Fest', desc: 'Pop-up kitchen takeover. Hand-pulled noodles and local craft brews by the water.', date: 'Apr 27', time: '12 PM', venue: 'Vallejo Waterfront', category: 'FOOD', lat: 38.1041, lng: -122.2566 },
  { id: 5, tag: 'THE TOWN', city: 'OAKLAND', title: 'Lake Merritt Jazz Sundays', desc: 'Live jazz by the lake. Bring a blanket, bring the family. Every Sunday all spring.', date: 'Apr 27', time: '2 PM', venue: 'Lake Merritt Amphitheater', category: 'MUSIC', lat: 37.8044, lng: -122.2512 },
  { id: 6, tag: 'SF', city: 'SF', title: 'Dolores Park Vinyl Market', desc: 'Crate diggers unite. Local DJs spinning while you browse rare wax and vintage gear.', date: 'Apr 27', time: '11 AM', venue: 'Dolores Park', category: 'CULTURE', lat: 37.7596, lng: -122.4269 },
  { id: 7, tag: 'RICHMOND', city: 'RICHMOND', title: 'Richmond Mural Walk + Live Paint', desc: 'Guided tour of new murals plus live painting by Bay Area artists. Free and open to all.', date: 'May 2', time: '3 PM', venue: 'Macdonald Ave', category: 'ART', lat: 37.9358, lng: -122.3477 },
  { id: 8, tag: 'THE TOWN', city: 'OAKLAND', title: 'Oaklandish Pop-Up Block Party', desc: 'Streetwear drops, local food trucks, DJ sets, and good energy in the heart of Uptown.', date: 'May 3', time: '4 PM', venue: 'Uptown Oakland', category: 'CULTURE', lat: 37.8083, lng: -122.2635 },
  { id: 9, tag: 'SAN JOSE', city: 'SAN JOSE', title: 'SoFA Street Fair: Live Music', desc: 'Five stages, thirty bands, all local. The South First Area comes alive for one big weekend.', date: 'May 3', time: '1 PM', venue: 'SoFA District', category: 'MUSIC', lat: 37.3333, lng: -121.8907 },
  { id: 10, tag: 'DALY CITY', city: 'DALY CITY', title: 'Westlake Night Market', desc: 'Filipino street food, boba, live performances, and community vendors under the lights.', date: 'May 4', time: '5 PM', venue: 'Westlake Shopping Center', category: 'FOOD', lat: 37.6879, lng: -122.4702 },
  { id: 11, tag: 'SF', city: 'SF', title: 'Chinatown After Dark', desc: 'Hidden bars, dim sum at midnight, and lion dancers in the alley. The city\'s best kept secret.', date: 'May 9', time: '8 PM', venue: 'Grant Ave', category: 'NIGHTLIFE', lat: 37.7941, lng: -122.4078 },
  { id: 12, tag: 'THE TOWN', city: 'OAKLAND', title: 'Grand Lake Farmers Market', desc: 'Fresh produce, live music, and community. Every Saturday morning rain or shine.', date: 'May 10', time: '9 AM', venue: 'Grand Lake', category: 'FOOD', lat: 37.8116, lng: -122.2466 },
  { id: 13, tag: 'SAN JOSE', city: 'SAN JOSE', title: 'Nikkei Matsuri Festival', desc: 'San Jose Japantown\'s annual celebration of Japanese American culture. Free admission with food, performances, and art. Paid 5K/10K run.', date: 'Apr 27', time: '10 AM', venue: 'San Jose Japantown', category: 'CULTURE', lat: 37.3492, lng: -121.8958 },
];

/* Live events — loaded from events.json, falls back to hardcoded */
const ALL_EVENTS = [...FALLBACK_EVENTS];
const _eventsLoading = { current: false, done: false, listeners: [] };

function loadLiveEvents() {
  if (_eventsLoading.current || _eventsLoading.done) return;
  _eventsLoading.current = true;

  fetch('events.json')
    .then(r => { if (!r.ok) throw new Error(`HTTP ${r.status}`); return r.json(); })
    .then(data => {
      if (data.events && data.events.length > 0) {
        ALL_EVENTS.length = 0;
        data.events.forEach(e => ALL_EVENTS.push(e));
        console.log(`[OnSumn] Loaded ${data.events.length} live events (generated ${data.generated})`);
      }
    })
    .catch(() => {
      console.log('[OnSumn] No events.json found, using fallback events');
    })
    .finally(() => {
      _eventsLoading.current = false;
      _eventsLoading.done = true;
      _eventsLoading.listeners.forEach(fn => fn());
      _eventsLoading.listeners = [];
    });
}

/* Hook to get events with loading state */
function useEvents() {
  const [events, setEvents] = React.useState(ALL_EVENTS);
  const [loading, setLoading] = React.useState(!_eventsLoading.done);

  React.useEffect(() => {
    if (_eventsLoading.done) {
      setEvents([...ALL_EVENTS]);
      setLoading(false);
      return;
    }
    loadLiveEvents();
    const listener = () => {
      setEvents([...ALL_EVENTS]);
      setLoading(false);
    };
    _eventsLoading.listeners.push(listener);
    return () => {
      const idx = _eventsLoading.listeners.indexOf(listener);
      if (idx >= 0) _eventsLoading.listeners.splice(idx, 1);
    };
  }, []);

  return { events, loading };
}

const CATEGORIES = ['ALL', 'MUSIC', 'ART', 'FOOD', 'NIGHTLIFE', 'CULTURE'];

const TAG_COLORS = {
  'THE TOWN': '#D57800', 'SF': '#FF4F00', 'SF MISSION': '#FF4F00',
  'SAN JOSE': '#395542', 'VALLEJO': '#7A99AC', 'RICHMOND': '#5A7A68', 'DALY CITY': '#5B7A8D',
};

function EventCard({ event, darkMode, index, radius }) {
  const [hov, setHov] = React.useState(false);
  const tagColor = TAG_COLORS[event.tag] || 'var(--international-orange)';
  const bgHues = [25, 15, 35, 200, 30, 20, 160, 40, 28, 190, 10, 45];
  const hue = bgHues[index % bgHues.length];

  return (
    <article
      onMouseEnter={() => setHov(true)}
      onMouseLeave={() => setHov(false)}
      style={{
        cursor: 'pointer',
        ...glassStyle(darkMode, 'card'),
        border: darkMode ? '1px solid rgba(255,255,255,0.08)' : '1px solid rgba(0,0,0,0.06)',
        borderRadius: radius,
        transition: 'transform 0.3s ease, box-shadow 0.3s ease',
        transform: hov ? 'translateY(-4px)' : 'none',
        boxShadow: hov
          ? (glassStyle(darkMode, 'card').boxShadow + `, 0 16px 40px rgba(${darkMode ? '0,0,0,0.4' : '0,0,0,0.1'})`)
          : glassStyle(darkMode, 'card').boxShadow,
        overflow: 'hidden',
        display: 'flex', flexDirection: 'column',
      }}
    >
      {/* Image area */}
      <div style={{
        height: 180, position: 'relative', overflow: 'hidden',
        background: `oklch(${darkMode ? 0.35 : 0.55} 0.05 ${hue})`,
        borderRadius: `${radius}px ${radius}px 0 0`,
      }}>
        {/* Date badge — glass pill */}
        <div style={{
          position: 'absolute', top: 12, left: 12,
          ...glassStyle(darkMode, 'btn'),
          border: darkMode ? '1px solid rgba(255,255,255,0.1)' : '1px solid rgba(255,255,255,0.3)',
          borderRadius: Math.max(radius - 4, 8),
          padding: '8px 12px', display: 'flex', flexDirection: 'column', alignItems: 'center',
        }}>
          <span style={{
            fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 800,
            color: '#fff', lineHeight: 1,
          }}>{event.date.split(' ')[1]}</span>
          <span style={{
            fontFamily: 'var(--font-body)', fontSize: 9, fontWeight: 600,
            letterSpacing: '0.08em', textTransform: 'uppercase',
            color: 'rgba(255,255,255,0.6)', marginTop: 2,
          }}>{event.date.split(' ')[0]}</span>
        </div>

        {/* Category badge */}
        <div style={{
          position: 'absolute', top: 12, right: 12,
          background: tagColor, color: '#fff',
          fontFamily: 'var(--font-body)', fontSize: 9, fontWeight: 700,
          letterSpacing: '0.1em', padding: '5px 10px',
          borderRadius: 100,
        }}>{event.category}</div>

        <span style={{
          position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: 'var(--font-body)', fontSize: 11, color: 'rgba(255,255,255,0.4)',
          letterSpacing: '0.05em',
        }}>Event Photo</span>
      </div>

      {/* Content */}
      <div style={{ padding: '16px 18px 20px', flex: 1, display: 'flex', flexDirection: 'column' }}>
        <div style={{
          fontFamily: 'var(--font-body)', fontSize: 10, fontWeight: 700,
          letterSpacing: '0.1em', textTransform: 'uppercase',
          color: tagColor, marginBottom: 8,
        }}>{event.tag}</div>

        <div style={{
          fontFamily: 'var(--font-display)', fontSize: 16, fontWeight: 700,
          color: darkMode ? 'var(--on-surface)' : '#1a1a1a',
          lineHeight: 1.25, marginBottom: 8,
        }}>{event.title}</div>

        <div style={{
          fontFamily: 'var(--font-body)', fontSize: 13, lineHeight: '20px',
          color: darkMode ? 'rgba(255,255,255,0.45)' : 'rgba(0,0,0,0.45)',
          flex: 1, marginBottom: 14,
        }}>{event.desc}</div>

        {/* Footer */}
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          borderTop: darkMode ? '1px solid rgba(255,255,255,0.06)' : '1px solid rgba(0,0,0,0.05)',
          paddingTop: 12,
        }}>
          <div>
            <div style={{ fontFamily: 'var(--font-body)', fontSize: 12, fontWeight: 600, color: darkMode ? '#fff' : '#333' }}>{event.time}</div>
            <div style={{ fontFamily: 'var(--font-body)', fontSize: 11, color: darkMode ? 'rgba(255,255,255,0.3)' : '#999' }}>{event.venue}</div>
          </div>
          <div style={{
            fontFamily: 'var(--font-body)', fontSize: 11, fontWeight: 700,
            letterSpacing: '0.05em', textTransform: 'uppercase',
            color: hov ? 'var(--international-orange)' : (darkMode ? 'rgba(255,255,255,0.25)' : '#ccc'),
            transition: 'color 0.2s',
          }}>I'M SLIDING →</div>
        </div>
      </div>
    </article>
  );
}

function EventsSection({ darkMode, activeCity, radius }) {
  const [activeCat, setActiveCat] = React.useState('ALL');
  const [showAll, setShowAll] = React.useState(false);

  const filtered = ALL_EVENTS.filter(e => {
    const cityMatch = activeCity === 'ALL' || e.city === activeCity;
    const catMatch = activeCat === 'ALL' || e.category === activeCat;
    return cityMatch && catMatch;
  });
  const visible = showAll ? filtered : filtered.slice(0, 8);

  return (
    <section style={{ padding: '80px 32px', maxWidth: 1280, margin: '0 auto' }}>
      {/* Header */}
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end',
        marginBottom: 40, flexWrap: 'wrap', gap: 16,
      }}>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8 }}>
            <div style={{ width: 4, height: 32, background: 'var(--international-orange)', borderRadius: 2 }} />
            <h2 style={{
              fontFamily: 'var(--font-display)', fontSize: 32, fontWeight: 700,
              color: darkMode ? 'var(--on-surface)' : '#1a1a1a', lineHeight: 1,
            }}>What's Good This Weekend</h2>
          </div>
          <p style={{
            fontFamily: 'var(--font-body)', fontSize: 14,
            color: darkMode ? 'rgba(255,255,255,0.35)' : '#999', marginLeft: 16,
          }}>Updated daily · Bay Area, CA</p>
        </div>

        {/* Glass category filter pills */}
        <div style={{
          display: 'inline-flex', gap: 2,
          ...glassStyle(darkMode, 'panel'),
          border: darkMode ? '1px solid rgba(255,255,255,0.08)' : '1px solid rgba(0,0,0,0.06)',
          borderRadius: radius, padding: 3,
        }}>
          {CATEGORIES.map(c => (
            <button key={c} onClick={() => { setActiveCat(c); setShowAll(false); }} style={{
              fontFamily: 'var(--font-body)', fontSize: 11, fontWeight: 600,
              letterSpacing: '0.05em', textTransform: 'uppercase',
              padding: '8px 14px', borderRadius: Math.max(radius - 4, 0),
              background: activeCat === c ? 'var(--international-orange)' : 'transparent',
              color: activeCat === c ? '#fff' : (darkMode ? 'rgba(255,255,255,0.4)' : 'rgba(0,0,0,0.4)'),
              border: 'none', cursor: 'pointer', transition: 'all 0.25s',
            }}>{c}</button>
          ))}
        </div>
      </div>

      {/* Grid */}
      {visible.length === 0 ? (
        <div style={{
          padding: '80px 32px', textAlign: 'center',
          fontFamily: 'var(--font-body)', fontSize: 16,
          color: darkMode ? 'rgba(255,255,255,0.25)' : '#ccc',
        }}>No events found for this filter.</div>
      ) : (
        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 20,
        }}>
          {visible.map((e, i) => <EventCard key={e.id} event={e} darkMode={darkMode} index={i} radius={radius} />)}
        </div>
      )}

      {/* Show more */}
      {!showAll && filtered.length > 8 && (
        <div style={{ textAlign: 'center', marginTop: 48 }}>
          <button onClick={() => setShowAll(true)} style={{
            fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 700,
            letterSpacing: '0.05em', textTransform: 'uppercase',
            padding: '14px 32px', borderRadius: radius,
            ...glassStyle(darkMode, 'btn'),
            border: darkMode ? '1px solid rgba(255,255,255,0.1)' : '1px solid rgba(0,0,0,0.08)',
            color: darkMode ? '#fff' : '#1a1a1a',
            cursor: 'pointer', transition: 'all 0.25s',
          }}
          onMouseEnter={e => { e.target.style.borderColor = 'var(--international-orange)'; e.target.style.color = 'var(--international-orange)'; }}
          onMouseLeave={e => { e.target.style.borderColor = darkMode ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.08)'; e.target.style.color = darkMode ? '#fff' : '#1a1a1a'; }}
          >View All Events ({filtered.length})</button>
        </div>
      )}
    </section>
  );
}

window.EventCard = EventCard;
window.EventsSection = EventsSection;
window.ALL_EVENTS = ALL_EVENTS;
window.FALLBACK_EVENTS = FALLBACK_EVENTS;
window.useEvents = useEvents;
window.loadLiveEvents = loadLiveEvents;
