// components/Chrome.jsx — Top nav, announcement bar, footer, tweaks, shared UI

// Hook: re-render when language changes
const useLang = () => {
  const [lang, setLangState] = React.useState(() => (window.__getLang && window.__getLang()) || 'en');
  React.useEffect(() => {
    if (!window.__onLangChange) return;
    return window.__onLangChange(setLangState);
  }, []);
  return lang;
};

const PAGE_KEYS = [
  { id: 'home',         key: 'nav.home' },
  { id: 'about',        key: 'nav.about' },
  // { id: 'team',         key: 'nav.team' },
  { id: 'resources',    key: 'nav.resources' },
  // { id: 'intercessors', key: 'nav.intercessors' },
  // { id: 'calendar',     key: 'nav.calendar' },
  // { id: 'prayer',       key: 'nav.prayer' },
  { id: 'give',         key: 'nav.give' },
];

const getPages = () => PAGE_KEYS.map(p => ({ id: p.id, label: (window.t && window.t(p.key)) || p.id }));

// Kept for legacy: some imports may still read PAGES
const PAGES = PAGE_KEYS.map(p => ({ id: p.id, label: p.id }));

const AnnouncementBar = () => {
  const [time, setTime] = React.useState(new Date());
  React.useEffect(() => {
    const id = setInterval(() => setTime(new Date()), 1000);
    return () => clearInterval(id);
  }, []);
  const sac = time.toLocaleTimeString('en-US', { timeZone: 'America/Los_Angeles', hour: 'numeric', minute: '2-digit', hour12: true });
  const [nextEvent, setNextEvent] = React.useState(null);
  React.useEffect(() => {
    fetch('/api/events')
      .then(r => r.json())
      .then(({ events }) => {
        const now = Date.now();
        const upcoming = (events || []).find(e => e.date && new Date(e.date).getTime() > now);
        if (upcoming) setNextEvent(upcoming);
      })
      .catch(() => {});
  }, []);
  const nextEventMsg = nextEvent
    ? `✦ Next gathering: ${nextEvent.name} · ${new Date(nextEvent.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'America/Los_Angeles' })} · ${nextEvent.location || ''}`
    : '✦ Next citywide gathering: check the calendar for upcoming events';
  const messages = [
    nextEventMsg,
    '✦ "Pray without ceasing" · 1 Thessalonians 5:17',
    '✦ Launching January 4, 2027 · register your church today',
    '✦ One church, one day, every other month · covering Greater Sacramento in prayer',
    '✦ "If my people, who are called by my name, will humble themselves and pray" · 2 Chronicles 7:14',
  ];
  const stream = [...messages, ...messages];
  return (
    <div style={{
      background: 'var(--ink)',
      color: 'var(--gold-soft)',
      fontFamily: 'var(--ff-mono)',
      fontSize: 12,
      letterSpacing: '0.14em',
      textTransform: 'uppercase',
      padding: '10px 0',
      overflow: 'hidden',
      display: 'flex',
      alignItems: 'center',
      gap: 24,
    }}>
      <div className="announcement-ticker-live" style={{
        display: 'inline-flex',
        alignItems: 'center',
        gap: 10,
        padding: '0 24px',
        borderRight: '1px solid rgba(242,183,5,0.3)',
        flexShrink: 0,
      }}>
        <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#21c55d' }} className="pulse-soft" />
        <span><span className="ticker-time">LIVE · {sac} </span><span className="ticker-loc">· SACRAMENTO</span><span className="ticker-live-mobile">LIVE</span></span>
      </div>
      <div className="announcement-ticker-messages" style={{ overflow: 'hidden', flex: 1 }}>
        <div style={{ display: 'inline-flex', gap: 40, animation: 'ticker 60s linear infinite', whiteSpace: 'nowrap' }}>
          {stream.map((m, i) => <span key={i}>{m}</span>)}
        </div>
      </div>
    </div>
  );
};

// Language switch — segmented EN / ES pill
const LangSwitch = ({ lang, onChange, block = false }) => {
  const opts = [
    { id: 'en', label: 'EN' },
    { id: 'es', label: 'ES' },
  ];
  return (
    <div
      role="group"
      aria-label="Language"
      style={{
        display: 'inline-flex',
        border: '1.5px solid rgba(242,183,5,0.5)',
        borderRadius: 999,
        padding: 3,
        background: 'rgba(11,45,92,0.4)',
        ...(block ? { width: '100%', justifyContent: 'center' } : {}),
      }}
    >
      {opts.map(o => {
        const active = lang === o.id;
        return (
          <button
            key={o.id}
            onClick={() => onChange(o.id)}
            aria-pressed={active}
            style={{
              padding: block ? '10px 20px' : '6px 14px',
              fontFamily: 'var(--ff-mono)',
              fontSize: 11,
              letterSpacing: '0.15em',
              fontWeight: 600,
              color: active ? 'var(--blue)' : 'var(--gold-soft)',
              background: active ? 'var(--gold)' : 'transparent',
              borderRadius: 999,
              minWidth: 44,
              transition: 'all 0.2s',
            }}
          >
            {o.label}
          </button>
        );
      })}
    </div>
  );
};

const TopNav = ({ current, onNavigate }) => {
  const [open, setOpen] = React.useState(false);
  const lang = useLang();
  const pages = getPages();
  const go = (p) => { setOpen(false); onNavigate(p); };
  const setLang = (l) => window.__setLang && window.__setLang(l);
  return (
  <header style={{
    position: 'sticky', top: 0, zIndex: 50,
    background: 'var(--blue)',
    color: 'var(--cream)',
    borderBottom: '3px solid var(--gold)',
  }}>
    <AnnouncementBar />
    <div className="u-container" style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '20px 40px', gap: 20,
    }}>
      <button onClick={() => go('home')} style={{
        display: 'flex', alignItems: 'center', gap: 14, color: 'var(--gold)', flexShrink: 1, minWidth: 0,
      }}>
        <LogoMark size={44} />
        <div style={{ textAlign: 'left', minWidth: 0 }}>
          <div className="nav-title" style={{
            fontFamily: 'var(--ff-display)', fontWeight: 700,
            letterSpacing: '0.06em', color: 'var(--gold)', lineHeight: 1,
            whiteSpace: 'nowrap',
          }}>SACRAMENTO PRAYS</div>
          <div className="nav-subtitle" style={{
            fontFamily: 'var(--ff-mono)', fontSize: 11, letterSpacing: '0.25em',
            color: 'var(--gold-soft)', marginTop: 4, whiteSpace: 'nowrap',
          }}>TWENTY-FOUR · SEVEN</div>
        </div>
      </button>
      {/* Desktop nav */}
      <nav className="desktop-only" style={{ display: 'flex', gap: 4 }}>
        {pages.map(p => {
          const active = current === p.id;
          return (
            <button
              key={p.id}
              onClick={() => go(p.id)}
              style={{
                padding: '10px 16px',
                fontFamily: 'var(--ff-body)',
                fontSize: 13,
                fontWeight: 500,
                letterSpacing: '0.04em',
                color: active ? 'var(--blue)' : 'var(--cream)',
                background: active ? 'var(--gold)' : 'transparent',
                borderRadius: 999,
                transition: 'all 0.2s',
              }}
              onMouseEnter={e => !active && (e.currentTarget.style.color = 'var(--gold)')}
              onMouseLeave={e => !active && (e.currentTarget.style.color = 'var(--cream)')}
            >
              {p.label}
            </button>
          );
        })}
      </nav>
      <div className="desktop-only" style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3 }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 4, fontFamily: 'var(--ff-mono)', fontSize: 9, letterSpacing: '0.18em', color: 'var(--gold-soft)', textTransform: 'uppercase', opacity: 0.7 }}>
            <svg viewBox="0 0 24 24" width={10} height={10} fill="none" stroke="currentColor" strokeWidth={1.8} strokeLinecap="round" strokeLinejoin="round">
              <circle cx="12" cy="12" r="10" />
              <ellipse cx="12" cy="12" rx="4" ry="10" />
              <line x1="2" y1="12" x2="22" y2="12" />
            </svg>
            {window.t ? window.t('nav.langLabel') : 'Language'}
          </span>
          <LangSwitch lang={lang} onChange={setLang} />
        </div>
        <button
          onClick={() => go('home')}
          className="btn btn-primary"
          style={{ padding: '12px 20px', fontSize: 12, flexShrink: 0 }}
        >
          {window.t ? window.t('nav.joinMovement') : '✦ Join the Movement'}
        </button>
      </div>

      {/* Mobile hamburger */}
      <button
        className="mobile-only"
        onClick={() => setOpen(o => !o)}
        aria-label="Menu"
        style={{
          width: 48, height: 48, borderRadius: 12,
          background: 'var(--gold)', color: 'var(--blue)',
          display: 'flex', flexDirection: 'column',
          alignItems: 'center', justifyContent: 'center', gap: 5,
          flexShrink: 0,
        }}
      >
        <span style={{ display: 'block', width: 22, height: 2.5, background: 'var(--blue)', borderRadius: 2, transition: 'transform 0.2s', transform: open ? 'rotate(45deg) translate(4px, 4px)' : 'none' }} />
        <span style={{ display: 'block', width: 22, height: 2.5, background: 'var(--blue)', borderRadius: 2, opacity: open ? 0 : 1 }} />
        <span style={{ display: 'block', width: 22, height: 2.5, background: 'var(--blue)', borderRadius: 2, transition: 'transform 0.2s', transform: open ? 'rotate(-45deg) translate(5px, -5px)' : 'none' }} />
      </button>
    </div>

    {/* Mobile drawer */}
    {open && (
      <div className="mobile-only" style={{
        background: 'var(--blue-deep)',
        borderTop: '1px solid rgba(242,183,5,0.2)',
        padding: '20px 20px 30px',
      }}>
        {pages.map(p => {
          const active = current === p.id;
          return (
            <button
              key={p.id}
              onClick={() => go(p.id)}
              style={{
                display: 'block', width: '100%', textAlign: 'left',
                padding: '16px 18px',
                fontFamily: 'var(--ff-display)', fontSize: 18,
                letterSpacing: '0.04em', textTransform: 'uppercase',
                color: active ? 'var(--gold)' : 'var(--cream)',
                background: active ? 'rgba(242,183,5,0.1)' : 'transparent',
                borderRadius: 10,
                borderLeft: active ? '3px solid var(--gold)' : '3px solid transparent',
                marginBottom: 4,
              }}
            >
              {p.label}
            </button>
          );
        })}
        <div style={{ marginTop: 16, padding: '0 18px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontFamily: 'var(--ff-mono)', fontSize: 10, letterSpacing: '0.18em', color: 'var(--gold-soft)', textTransform: 'uppercase', marginBottom: 8 }}>
            <svg viewBox="0 0 24 24" width={13} height={13} fill="none" stroke="currentColor" strokeWidth={1.8} strokeLinecap="round" strokeLinejoin="round">
              <circle cx="12" cy="12" r="10" />
              <ellipse cx="12" cy="12" rx="4" ry="10" />
              <line x1="2" y1="12" x2="22" y2="12" />
            </svg>
            {window.t ? window.t('nav.langLabel') : 'Language / Idioma'}
          </div>
          <LangSwitch lang={lang} onChange={setLang} block />
        </div>
        <button
          onClick={() => go('home')}
          className="btn btn-primary"
          style={{ width: '100%', marginTop: 16, justifyContent: 'center' }}
        >
          {window.t ? window.t('nav.joinMovement') : '✦ Join the Movement'}
        </button>
      </div>
    )}
  </header>
  );
};

const PreFooterCTA = ({ onNavigate }) => {
  const lang = useLang(); // eslint-disable-line no-unused-vars
  const T = window.t || (k => k);
  return (
    <section className="prefooter-section" style={{
      background: 'var(--beige-2)',
      borderTop: '2px solid rgba(11,45,92,0.15)',
      borderBottom: '2px solid rgba(11,45,92,0.15)',
      padding: 'clamp(48px, 7vw, 80px) 0',
    }}>
      <div className="u-container prefooter-inner" style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        gap: 32, flexWrap: 'wrap',
      }}>
        <div style={{ flex: '1 1 320px' }}>
          <div className="u-eyebrow" style={{ marginBottom: 12 }}>{T('prefooter.eyebrow')}</div>
          <h2 className="h-display h-section" style={{
            fontSize: 'clamp(28px, 4.5vw, 44px)',
            color: 'var(--blue)', margin: 0, textTransform: 'uppercase', lineHeight: 1.05,
          }}>
            {T('prefooter.title')}
          </h2>
        </div>
        <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
          <button className="btn btn-primary" onClick={() => { onNavigate('home'); setTimeout(() => document.getElementById('register-form')?.scrollIntoView({ behavior: 'smooth', block: 'start' }), 100); }}>{T('prefooter.ctaAdopt')}</button>
          <button className="btn btn-ghost" onClick={() => onNavigate('give')}>{T('prefooter.ctaGive')}</button>
        </div>
      </div>
    </section>
  );
};

const Footer = ({ onNavigate }) => {
  const lang = useLang(); // eslint-disable-line no-unused-vars
  const T = window.t || (k => k);
  const neighborhoodsLine = T('footer.neighborhoodsLine');
  return (
  <footer style={{
    background: 'var(--grad-blue)',
    color: 'var(--cream)',
    padding: 'clamp(48px, 6vw, 72px) 0 32px',
    borderTop: '6px solid var(--gold)',
  }}>
    <div className="u-container">
      <div className="footer-main" style={{
        display: 'grid', gridTemplateColumns: '1.6fr 1fr 1fr', gap: 'clamp(28px, 4vw, 56px)',
        marginBottom: 40,
      }}>
        {/* Brand block */}
        <div>
          <LogoMark size={48} />
          <h3 style={{
            fontFamily: 'var(--ff-display)', fontSize: 22, color: 'var(--gold)',
            margin: '16px 0 6px', letterSpacing: '0.02em',
          }}>
            SacramentoPrays247.org
          </h3>
          <p className="h-elegant" style={{ fontSize: 16, color: 'var(--gold-soft)', margin: '0 0 16px' }}>
            "{T('footer.tagline')}"
          </p>
          <a href="https://citypastors.net" target="_blank" rel="noopener noreferrer"
            style={{ fontFamily: 'var(--ff-mono)', fontSize: 11, letterSpacing: '0.12em', color: 'var(--gold)', textTransform: 'uppercase', borderBottom: '1px solid rgba(242,183,5,0.4)', paddingBottom: 2 }}>
            City Pastors Fellowship →
          </a>
        </div>

        {/* Get Involved */}
        <div>
          <div style={{ fontFamily: 'var(--ff-mono)', fontSize: 11, letterSpacing: '0.2em', color: 'var(--gold)', textTransform: 'uppercase', marginBottom: 14 }}>
            {T('footer.getInvolved')}
          </div>
          <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 8, fontSize: 14, opacity: 0.85, lineHeight: 1.5 }}>
            <li><button onClick={() => { onNavigate('home'); setTimeout(() => document.getElementById('register-form')?.scrollIntoView({ behavior: 'smooth', block: 'start' }), 100); }} style={{ color: 'var(--cream)', fontSize: 14 }}>{T('involved.registerChurch')}</button></li>
            <li><button onClick={() => onNavigate('give')} style={{ color: 'var(--cream)', fontSize: 14 }}>{T('involved.give')}</button></li>
          </ul>
        </div>

        {/* Contact */}
        <div>
          <div style={{ fontFamily: 'var(--ff-mono)', fontSize: 11, letterSpacing: '0.2em', color: 'var(--gold)', textTransform: 'uppercase', marginBottom: 14 }}>
            {T('footer.contact')}
          </div>
          <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 8, fontSize: 14, opacity: 0.85, lineHeight: 1.5 }}>
            <li><a href="mailto:don@citypastors.net" style={{ color: 'var(--cream)' }}>don@citypastors.net</a></li>
            <li>{T('footer.location')}</li>
            <li style={{ marginTop: 8 }}>
              <button onClick={() => onNavigate('about')} style={{ color: 'var(--gold)', fontSize: 13, borderBottom: '1px solid rgba(242,183,5,0.4)', paddingBottom: 2 }}>{T('footer.aboutLink')}</button>
            </li>
          </ul>
        </div>
      </div>

      {/* Neighborhoods, single line of fine print */}
      <div style={{
        borderTop: '1px solid rgba(242,183,5,0.2)',
        paddingTop: 20, marginBottom: 20,
        fontFamily: 'var(--ff-body)', fontSize: 13,
        color: 'var(--gold-soft)', opacity: 0.7, lineHeight: 1.6,
      }}>
        {neighborhoodsLine}
      </div>

      {/* Legal */}
      <div className="footer-legal" style={{
        borderTop: '1px solid rgba(242,183,5,0.2)',
        paddingTop: 20,
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        fontFamily: 'var(--ff-mono)', fontSize: 10, letterSpacing: '0.15em',
        color: 'var(--gold-soft)', textTransform: 'uppercase',
        opacity: 0.7, gap: 16, flexWrap: 'wrap',
      }}>
        <div>{T('footer.rights')}</div>
        <div>{T('footer.motto')}</div>
      </div>
    </div>
  </footer>
  );
};

// Image with Unsplash URL and loading + placeholder fallback
const Img = ({ src, alt, label, style = {}, ratio = '4/3', objectPosition = 'center' }) => (
  <div style={{
    position: 'relative',
    aspectRatio: ratio,
    overflow: 'hidden',
    background: 'var(--beige-2)',
    ...style,
  }}>
    <img
      src={src}
      alt={alt}
      style={{
        width: '100%', height: '100%', objectFit: 'cover',
        objectPosition,
      }}
      loading="lazy"
    />
    {label && (
      <div style={{
        position: 'absolute', left: 10, bottom: 10,
        background: 'rgba(11,45,92,0.85)', color: 'var(--gold-soft)',
        fontFamily: 'var(--ff-mono)', fontSize: 10, letterSpacing: '0.15em',
        padding: '4px 10px', borderRadius: 999, textTransform: 'uppercase',
      }}>{label}</div>
    )}
  </div>
);

// Monospace image placeholder (used on interior pages)
const ImgSlot = ({ label, ratio = '4/3', style = {} }) => (
  <div className="img-placeholder" style={{ aspectRatio: ratio, ...style }}>
    [ {label} ]
  </div>
);

Object.assign(window, { TopNav, Footer, PreFooterCTA, AnnouncementBar, Img, ImgSlot, PAGES });
