// App.jsx — shell, router, Tweaks, shared chrome
// Tweaks state is stored on window.__wbbq so all page components can read it.

const { useState, useEffect, useRef, createContext, useContext } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "heroVariant": "poster",
  "accent": "flame",
  "chaos": true,
  "tagline": "We cook pig. You eat it. Everybody wins except the pig.",
  "featuredMascot": "rotate"
}/*EDITMODE-END*/;

const TweaksContext = createContext(TWEAK_DEFAULTS);
window.useTweaks = () => useContext(TweaksContext);

// ---------- Router ----------
const ROUTES = [
  { path: '',          label: 'Home',     component: 'HomePage' },
  { path: 'team',      label: 'Team',     component: 'TeamPage' },
  { path: 'events',    label: 'Events',   component: 'EventsPage' },
  { path: 'trophies',  label: 'Trophies', component: 'TrophiesPage' },
  { path: 'stats',     label: 'Stats',    component: 'StatsPage' },
  { path: 'merch',     label: 'Merch',    component: 'MerchPage', feature: 'merch' },
  { path: 'blog',      label: 'Field Notes', component: 'BlogPage' },
  { path: 'app',       label: 'Sausage Calc', component: 'AppPage' },
  { path: 'contact',   label: 'Contact',  component: 'ContactPage' },
];

// Nav visibility: excludes hidden + feature-gated-off routes. Used for header/footer lists.
const isRouteAvailable = (r) => !r.hidden && (!r.feature || (window.featureEnabled && window.featureEnabled(r.feature)));

// Route resolvability: hidden routes are still reachable by direct URL, only feature flags redirect.
const isRouteResolvable = (r) => !r.feature || (window.featureEnabled && window.featureEnabled(r.feature));

const useRoute = () => {
  const [route, setRoute] = useState(() => (location.hash.replace('#/', '').replace('#', '') || ''));
  useEffect(() => {
    const onHash = () => {
      setRoute(location.hash.replace('#/', '').replace('#', '') || '');
      window.scrollTo({ top: 0, behavior: 'instant' });
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);
  return route;
};
window.useRoute = useRoute;

// ---------- Scroll reveal ----------
window.useReveal = () => {
  useEffect(() => {
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) e.target.classList.add('in'); });
    }, { threshold: 0.15 });
    document.querySelectorAll('.reveal:not(.in)').forEach((el) => io.observe(el));
    return () => io.disconnect();
  });
};

// ---------- KCBS achievement tiers ----------
// place: "1", "1st", "Rookie Of The Year", etc. kind: 'overall' | 'meat'.
// Returns { tier, label, color, emoji } or null.
window.tierFor = (place, kind = 'overall') => {
  if (place == null || place === '') return null;
  const s = String(place).trim();
  if (/rookie of/i.test(s)) return { tier: 'rookie', label: 'ROOKIE', color: 'var(--wbbq-flame)', emoji: '🏆' };
  const n = parseInt(s, 10);
  if (!Number.isFinite(n) || n < 1) return null;
  if (kind === 'overall') {
    if (n === 1) return { tier: 'gc',   label: 'GC',   color: 'var(--wbbq-flame)', emoji: '🏆' };
    if (n === 2) return { tier: 'rgc',  label: 'RGC',  color: 'var(--wbbq-slime)', emoji: null };
    if (n <= 10) return { tier: 'call', label: 'CALL', color: 'var(--wbbq-blue)',  emoji: null };
    return null;
  }
  if (n <= 10) return { tier: 'call', label: 'CALL', color: 'var(--wbbq-blue)', emoji: null };
  return null;
};

window.TierPill = ({ tier, size = 'sm' }) => {
  if (!tier) return null;
  const fs = size === 'lg' ? 11 : 9;
  const pad = size === 'lg' ? '3px 9px' : '2px 7px';
  return (
    <span style={{
      fontFamily: 'var(--font-display)', fontSize: fs, letterSpacing: '0.14em',
      padding: pad, border: `1.5px solid ${tier.color}`, color: tier.color,
      textTransform: 'uppercase', lineHeight: 1.2, whiteSpace: 'nowrap',
      display: 'inline-block',
    }}>{tier.label}</span>
  );
};

// ---------- Header ----------
const Header = ({ route }) => {
  const [open, setOpen] = useState(false);
  const currentPath = route;
  // Close the drawer whenever the route changes (useRoute already scrolls to top).
  useEffect(() => { setOpen(false); }, [route]);
  const navLinks = ROUTES.filter(r => r.path !== '' && isRouteAvailable(r));
  const showAdmin = window.location.hostname !== 'compteam.warpedbbq.com';
  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 80,
      background: 'rgba(11,11,12,0.92)',
      backdropFilter: 'blur(8px)',
      borderBottom: '1px solid var(--border)',
    }}>
      <div className="wrap" style={{
        padding: '14px 20px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16,
      }}>
        <a href="#/" style={{ display: 'flex', alignItems: 'center', gap: 10, textDecoration: 'none', flexShrink: 0 }}>
          <img src={`${window.ASSETS}brand/wordmark.png`} alt="Warped BBQ" style={{ height: 36 }} />
        </a>
        <nav className={`nav-links${open ? ' nav-links-open' : ''}`} style={{ display: 'flex', gap: 22, fontFamily: 'var(--font-display)', fontSize: 12, letterSpacing: '0.14em', textTransform: 'uppercase', flexWrap: 'wrap', justifyContent: 'center' }}>
          {navLinks.map((r) => (
            <a key={r.path} href={`#/${r.path}`} style={{
              color: currentPath === r.path ? 'var(--wbbq-flame)' : 'var(--fg1)',
              textDecoration: 'none',
              position: 'relative',
              paddingBottom: 2,
              borderBottom: currentPath === r.path ? '2px solid var(--wbbq-flame)' : '2px solid transparent',
              transition: 'color 120ms, border-color 120ms',
            }}>{r.label}</a>
          ))}
          {/* Inside-drawer CTAs — shown only when .nav-links-open on mobile, no-op on desktop (dup hidden by header-cta-desktop) */}
          <a className="drawer-insta" href="https://instagram.com/warpedbbq" target="_blank" rel="noreferrer" style={{ display: 'none' }}>@warpedbbq</a>
          {showAdmin && (
            <a className="drawer-cta" href={window.ADMIN_URL || 'https://admin.compteam.warpedbbq.com'} style={{ display: 'none', textDecoration: 'none' }}>↗ Admin</a>
          )}
        </nav>
        <a className="header-cta-desktop" href="https://instagram.com/warpedbbq" target="_blank" rel="noreferrer" style={{
          padding: '10px 18px', fontSize: 12, boxShadow: '4px 4px 0 var(--wbbq-blue)', flexShrink: 0,
          fontFamily: 'var(--font-display)', letterSpacing: '0.14em', textTransform: 'uppercase', textDecoration: 'none',
          background: 'var(--wbbq-flame)', color: 'var(--wbbq-black)', border: '2px solid var(--wbbq-flame)',
        }}>
          @warpedbbq
        </a>
        {showAdmin && (
          <a className="header-cta-desktop" href={window.ADMIN_URL || 'https://admin.compteam.warpedbbq.com'} style={{
            fontFamily: 'var(--font-display)', fontSize: 11, letterSpacing: '0.14em',
            textTransform: 'uppercase', textDecoration: 'none',
            padding: '8px 12px',
            color: 'var(--wbbq-slime)',
            border: '2px solid var(--wbbq-slime)',
            flexShrink: 0,
          }}>↗ Admin</a>
        )}
        <button
          className="mobile-nav-toggle"
          onClick={() => setOpen(o => !o)}
          aria-label={open ? 'Close menu' : 'Open menu'}
          aria-expanded={open}
          style={{
            background: 'transparent', border: '2px solid var(--wbbq-flame)',
            color: 'var(--wbbq-flame)', width: 40, height: 40,
            alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
            flexShrink: 0, padding: 0,
          }}
        >
          <span style={{ fontFamily: 'var(--font-display)', fontSize: 18, lineHeight: 1, transform: 'translateY(-1px)' }}>{open ? '✕' : '☰'}</span>
        </button>
      </div>
    </header>
  );
};
window.Header = Header;

// ---------- UFO flyby (decorative, above content) ----------
const UfoFlyby = () => {
  const tweaks = useTweaks();
  if (!tweaks.chaos) return null;
  return (
    <img src={`${window.ASSETS}mascots/ufo.svg`} alt="" aria-hidden="true" style={{
      position: 'fixed', top: '18%', left: 0, width: 120, zIndex: 60,
      pointerEvents: 'none',
      animation: 'ufo-fly 22s linear infinite',
      animationDelay: '3s',
      filter: 'drop-shadow(0 0 24px rgba(181,238,28,0.5))',
    }} />
  );
};
window.UfoFlyby = UfoFlyby;

// ---------- Footer ----------
const Footer = () => (
  <footer style={{
    position: 'relative', zIndex: 2,
    background: 'var(--wbbq-ink)',
    borderTop: '3px solid var(--wbbq-flame)',
    padding: '60px 0 40px',
    marginTop: 40,
  }}>
    <div className="wrap" style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 40 }}>
      <div>
        <img src={`${window.ASSETS}brand/wordmark.png`} alt="Warped BBQ" style={{ width: 220, marginBottom: 18 }} />
        <p style={{ color: 'var(--fg2)', fontSize: 14, margin: 0, maxWidth: 280 }}>
          Competition BBQ out of Eastern Connecticut. We smoke. You eat. Everybody wins except the pig.
        </p>
      </div>
      <div>
        <h4 style={{ fontFamily: 'var(--font-display)', fontSize: 14, color: 'var(--wbbq-blue)', letterSpacing: '0.14em', margin: '0 0 16px' }}>Go Places</h4>
        <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'grid', gap: 8 }}>
          {ROUTES.filter(r => r.path !== '' && isRouteAvailable(r)).map((r) => (
            <li key={r.path}><a href={`#/${r.path}`} style={{ color: 'var(--fg1)', fontSize: 13, textDecoration: 'none' }}>{r.label}</a></li>
          ))}
        </ul>
      </div>
      <div>
        <h4 style={{ fontFamily: 'var(--font-display)', fontSize: 14, color: 'var(--wbbq-blue)', letterSpacing: '0.14em', margin: '0 0 16px' }}>Find Us</h4>
        <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'grid', gap: 8, color: 'var(--fg1)', fontSize: 13 }}>
          <li>Eastern Connecticut</li>
          <li><a href="https://instagram.com/warpedbbq" target="_blank" rel="noreferrer" style={{ color: 'var(--wbbq-flame)', textDecoration: 'none' }}>@warpedbbq on Instagram</a></li>
          <li><a href="https://sausagecalculator.warpedbbq.com" target="_blank" rel="noreferrer" style={{ color: 'var(--wbbq-slime)', textDecoration: 'none' }}>Sausage Calculator ↗</a></li>
        </ul>
      </div>
      <div>
        <h4 style={{ fontFamily: 'var(--font-display)', fontSize: 14, color: 'var(--wbbq-blue)', letterSpacing: '0.14em', margin: '0 0 16px' }}>Transmissions</h4>
        <p style={{ color: 'var(--fg2)', fontSize: 13, margin: '0 0 12px' }}>Drop your email. We'll holler when we cook.</p>
        <form onSubmit={(e) => { e.preventDefault(); alert('You are on the list. Stay hungry.'); }} style={{ display: 'flex', gap: 0 }}>
          <input type="email" required placeholder="you@pit.gov" style={{
            flex: 1, padding: '10px 12px', background: 'var(--wbbq-black)',
            border: '2px solid var(--border)', borderRight: 0, color: 'var(--fg1)',
            fontFamily: 'var(--font-body)', fontSize: 13,
          }} />
          <button type="submit" style={{
            background: 'var(--wbbq-flame)', color: 'var(--wbbq-black)',
            border: '2px solid var(--wbbq-flame)',
            padding: '10px 14px', fontFamily: 'var(--font-display)', fontSize: 12,
            letterSpacing: '0.08em', textTransform: 'uppercase', cursor: 'pointer',
          }}>Yell</button>
        </form>
      </div>
    </div>
    <div className="wrap" style={{ marginTop: 48, paddingTop: 20, borderTop: '1px solid var(--border)', display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between', gap: 12, color: 'var(--fg3)', fontSize: 12 }}>
      <div>© {new Date().getFullYear()} WARPED BBQ · MADE IN EASTERN CT · NOT RESPONSIBLE FOR ABDUCTIONS</div>
      <div style={{ fontFamily: 'var(--font-mono)' }}>v2.0 · SMOKED, SAUCED, AND SOON</div>
    </div>
    <div className="wrap" style={{ marginTop: 14, color: 'var(--fg3)', fontSize: 11, fontFamily: 'var(--font-mono)', display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between', gap: 12 }}>
      <span>Built by <a href="https://warpedtechnologies.io" target="_blank" rel="noreferrer" style={{ color: 'var(--wbbq-blue)' }}>Warped Technologies</a></span>
      <span>Display font by <a href="https://www.onlinewebfonts.com/author/Ryan_Martinson" target="_blank" rel="noreferrer" style={{ color: 'var(--fg2)' }}>Ryan Martinson</a> via <a href="http://www.onlinewebfonts.com" target="_blank" rel="noreferrer" style={{ color: 'var(--fg2)' }}>Web Fonts</a>, CC BY 4.0.</span>
    </div>
  </footer>
);
window.Footer = Footer;

// ---------- Tweaks panel ----------
const TweaksPanel = ({ tweaks, setTweaks, visible }) => {
  if (!visible) return null;
  const set = (k, v) => {
    const next = { ...tweaks, [k]: v };
    setTweaks(next);
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [k]: v } }, '*');
  };
  const toggleRow = (key, options) => (
    <div className="tw-row">
      {options.map(([v, label]) => (
        <button key={v} className={`tw-btn ${tweaks[key] === v ? 'active' : ''}`} onClick={() => set(key, v)}>{label}</button>
      ))}
    </div>
  );
  return (
    <div className="tweaks-panel">
      <h4>◉ Tweaks</h4>
      <label>Hero Variant</label>
      {toggleRow('heroVariant', [['poster','Poster'],['marquee','Marquee'],['abduction','Abduct']])}
      <label>Accent</label>
      {toggleRow('accent', [['flame','Flame'],['slime','Slime'],['blood','Blood']])}
      <label>Featured Mascot</label>
      {toggleRow('featuredMascot', [['rotate','Rotate'],['pig','Pig'],['flame','Flame'],['ufo','UFO']])}
      <label>Chaos Mode (motion)</label>
      {toggleRow('chaos', [[true,'On'],[false,'Off']])}
      <label>Hero Tagline</label>
      <input type="text" value={tweaks.tagline} onChange={(e) => set('tagline', e.target.value)} />
    </div>
  );
};

// ---------- App shell ----------
const App = () => {
  const [tweaks, setTweaks] = useState(TWEAK_DEFAULTS);
  const [editMode, setEditMode] = useState(false);
  const route = useRoute();

  useEffect(() => {
    const onMsg = (e) => {
      if (e.data?.type === '__activate_edit_mode') setEditMode(true);
      if (e.data?.type === '__deactivate_edit_mode') setEditMode(false);
    };
    window.addEventListener('message', onMsg);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);

  // Apply accent as CSS variable so components can reference --accent-dynamic
  useEffect(() => {
    const map = { flame: '#FF7A1A', slime: '#B5EE1C', blood: '#B11D1D' };
    document.documentElement.style.setProperty('--accent-dynamic', map[tweaks.accent] || map.flame);
    document.documentElement.style.setProperty('--accent-dynamic-hot', tweaks.accent === 'flame' ? '#FFB21A' : tweaks.accent === 'slime' ? '#D8FF5A' : '#E84B4B');
  }, [tweaks.accent]);

  let PageComponent;
  if (route.startsWith('blog/')) {
    PageComponent = window.BlogPostPage || window.BlogPage || window.HomePage;
  } else if (route.startsWith('docs/')) {
    PageComponent = window.DocsPage || window.HomePage;
  } else {
    PageComponent = window[(ROUTES.find(r => r.path === route && isRouteResolvable(r)) || ROUTES[0]).component] || window.HomePage;
  }

  return (
    <TweaksContext.Provider value={tweaks}>
      <div className="stars" />
      <Header route={route} />
      <UfoFlyby />
      <main style={{ position: 'relative', zIndex: 2, minHeight: '70vh' }}>
        <PageComponent />
      </main>
      <Footer />
      <TweaksPanel tweaks={tweaks} setTweaks={setTweaks} visible={editMode} />
    </TweaksContext.Provider>
  );
};

window.WarpedApp = App;
