// components/NewsTicker.jsx
// A right-to-left news marquee that sits directly under the top nav, sitewide.
// Pulls the latest 5 press releases from /api/news (which proxies the IR RSS
// feed) and links each headline out to ir.wrap.com in a new tab. Ends with a
// "MORE NEWS" CTA to the full releases page.
//
// Conventions followed (see CLAUDE.md):
//   - Babel-in-browser, no build step
//   - Hooks aliased to avoid CDN-global collisions
//   - Inline React style objects, design tokens (no hardcoded brand hex)
//   - Exported on window at the bottom via Object.assign

const {
    useState: useNTState,
    useEffect: useNTEffect,
    useRef: useNTRef,
} = React;

const NEWS_ENDPOINT = '/api/news';
const RELEASES_URL = 'https://ir.wrap.com/news-events/news-releases';

function NewsTicker() {
    const [items, setItems] = useNTState([]);
    const [paused, setPaused] = useNTState(false);
    const [dismissed, setDismissed] = useNTState(false);
    const mounted = useNTRef(true);
    const barRef = useNTRef(null);

    // Publish the ticker's rendered height as --ticker-h on <html> so the fixed
    // nav (top: var(--ticker-h)) and page content (#root padding) sit below it.
    // Runs every render (no deps) so it re-measures after items load and after a
    // dismiss. When the bar isn't rendered — no items, dismissed, or unmounted
    // (e.g. wraptormx) — barRef is null, --ticker-h becomes 0px, and the nav and
    // content slide up to reclaim the space automatically.
    useNTEffect(() => {
        const root = document.documentElement;
        const setVar = () => {
            const h = barRef.current ? barRef.current.offsetHeight : 0;
            root.style.setProperty('--ticker-h', h ? h + 'px' : '0px');
        };
        setVar();
        window.addEventListener('resize', setVar);
        return () => {
            window.removeEventListener('resize', setVar);
            root.style.setProperty('--ticker-h', '0px');
        };
    });

    useNTEffect(() => {
        mounted.current = true;
        fetch(NEWS_ENDPOINT)
            .then((r) => (r.ok ? r.json() : { items: [] }))
            .then((data) => {
                if (mounted.current && data && Array.isArray(data.items)) {
                    setItems(data.items);
                }
            })
            .catch(() => {
                /* fail soft: ticker simply doesn't render */
            });
        return () => {
            mounted.current = false;
        };
    }, []);

    // Nothing to show → render nothing (no empty bar, no layout shift beyond this).
    // Dismissed → same: barRef goes null, --ticker-h drops to 0px, nav/content rise.
    if (dismissed || !items || items.length === 0) return null;

    // Respect users who prefer no motion: show a static, scrollable strip.
    const prefersReducedMotion =
        typeof window !== 'undefined' &&
        window.matchMedia &&
        window.matchMedia('(prefers-reduced-motion: reduce)').matches;

    const separator = (
        <span
            aria-hidden="true"
            style={{
                color: 'var(--accent)',
                margin: '0 1.25rem',
                fontSize: '0.6rem',
                transform: 'translateY(-1px)',
            }}
        >
      &#9670;
    </span>
    );

    const renderItem = (item, i) => (
        <a
            key={`${item.link}-${i}`}
            href={item.link}
            target="_blank"
            rel="noopener noreferrer"
            style={{
                color: 'var(--text)',
                textDecoration: 'none',
                fontFamily: "'DM Sans', sans-serif",
                fontSize: '0.82rem',
                letterSpacing: '0.01em',
                whiteSpace: 'nowrap',
                opacity: 0.92,
                transition: 'opacity 0.15s ease, color 0.15s ease',
            }}
            onMouseEnter={(e) => {
                e.currentTarget.style.color = 'var(--accent)';
                e.currentTarget.style.opacity = '1';
            }}
            onMouseLeave={(e) => {
                e.currentTarget.style.color = 'var(--text)';
                e.currentTarget.style.opacity = '0.92';
            }}
        >
            {item.title}
        </a>
    );

    // One "track" = all items with separators between them. We render the track
    // twice inside the moving strip so the loop is seamless (as the first copy
    // scrolls off the left, the second is already filling from the right).
    const buildTrack = (keyPrefix) =>
        items.map((item, i) => (
            <span key={`${keyPrefix}-${i}`} style={{ display: 'inline-flex', alignItems: 'center' }}>
        {renderItem(item, i)}
                {separator}
      </span>
        ));

    const animationName = 'wrapTickerScroll';
    // Duration scales with number of items so speed feels consistent regardless
    // of how many releases come back (~10s per headline for a calm, readable pace).
    const durationSec = Math.max(40, items.length * 10);

    return (
        <div
            ref={barRef}
            role="region"
            aria-label="Latest WRAP press releases"
            style={{
                background: 'var(--bg, #060C1C)',
                borderBottom: '1px solid rgba(255,181,5,0.18)',
                overflow: 'hidden',
                position: 'fixed',
                top: 0,
                left: 0,
                right: 0,
                zIndex: 201, // above the nav (200): the bar sits at the very top
                width: '100%',
            }}
        >
            {/* Inline keyframes + hover-pause; scoped by the animation name. */}
            <style>{`
        @keyframes ${animationName} {
          0%   { transform: translateX(0); }
          100% { transform: translateX(-50%); }
        }
        .wrap-ticker-strip {
          display: inline-flex;
          align-items: center;
          white-space: nowrap;
          will-change: transform;
          animation: ${animationName} ${durationSec}s linear infinite;
        }
        .wrap-ticker-strip.is-paused { animation-play-state: paused; }
        .wrap-ticker-viewport:hover .wrap-ticker-strip { animation-play-state: paused; }
      `}</style>

            <div
                style={{
                    display: 'flex',
                    alignItems: 'stretch',
                    width: '100%',
                }}
            >
                {/* LATEST label */}
                <div
                    style={{
                        flex: '0 0 auto',
                        display: 'flex',
                        alignItems: 'center',
                        background: 'var(--accent, #FFB505)',
                        color: 'var(--bg, #060C1C)',
                        fontFamily: "'Barlow Condensed', sans-serif",
                        fontWeight: 800,
                        textTransform: 'uppercase',
                        letterSpacing: '0.08em',
                        fontSize: '0.8rem',
                        padding: '0.4rem 0.9rem',
                        zIndex: 2,
                    }}
                >
                    Latest
                </div>

                {/* Moving viewport */}
                <div
                    className="wrap-ticker-viewport"
                    style={{
                        flex: '1 1 auto',
                        overflow: prefersReducedMotion ? 'auto' : 'hidden',
                        padding: '0.4rem 0',
                        position: 'relative',
                    }}
                >
                    {prefersReducedMotion ? (
                        <div style={{ display: 'inline-flex', alignItems: 'center', paddingLeft: '1rem' }}>
                            {buildTrack('static')}
                        </div>
                    ) : (
                        <div
                            className={`wrap-ticker-strip${paused ? ' is-paused' : ''}`}
                            onFocus={() => setPaused(true)}
                            onBlur={() => setPaused(false)}
                            style={{ paddingLeft: '1rem' }}
                        >
                            {/* Two identical tracks for a seamless -50% loop */}
                            {buildTrack('a')}
                            {buildTrack('b')}
                        </div>
                    )}
                </div>

                {/* MORE NEWS CTA */}
                <a
                    href={RELEASES_URL}
                    target="_blank"
                    rel="noopener noreferrer"
                    style={{
                        flex: '0 0 auto',
                        display: 'flex',
                        alignItems: 'center',
                        gap: '0.35rem',
                        background: 'rgba(255,181,5,0.1)',
                        color: 'var(--accent, #FFB505)',
                        fontFamily: "'Barlow Condensed', sans-serif",
                        fontWeight: 700,
                        textTransform: 'uppercase',
                        letterSpacing: '0.06em',
                        fontSize: '0.78rem',
                        textDecoration: 'none',
                        padding: '0.4rem 0.9rem',
                        borderLeft: '1px solid rgba(255,181,5,0.18)',
                        whiteSpace: 'nowrap',
                        zIndex: 2,
                    }}
                    onMouseEnter={(e) => {
                        e.currentTarget.style.background = 'rgba(255,181,5,0.2)';
                    }}
                    onMouseLeave={(e) => {
                        e.currentTarget.style.background = 'rgba(255,181,5,0.1)';
                    }}
                >
                    More News <span aria-hidden="true">&rarr;</span>
                </a>

                {/* Close / dismiss — hides the whole bar for this page load */}
                <button
                    type="button"
                    aria-label="Dismiss news bar"
                    title="Dismiss"
                    onClick={() => setDismissed(true)}
                    style={{
                        flex: '0 0 auto',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        width: 40,
                        background: 'transparent',
                        color: 'var(--text-sub, #8899bb)',
                        border: 'none',
                        borderLeft: '1px solid rgba(255,181,5,0.18)',
                        cursor: 'pointer',
                        fontSize: '1.1rem',
                        lineHeight: 1,
                        padding: 0,
                        transition: 'color 0.15s ease, background 0.15s ease',
                    }}
                    onMouseEnter={(e) => {
                        e.currentTarget.style.color = 'var(--text, #e8edf8)';
                        e.currentTarget.style.background = 'rgba(255,255,255,0.05)';
                    }}
                    onMouseLeave={(e) => {
                        e.currentTarget.style.color = 'var(--text-sub, #8899bb)';
                        e.currentTarget.style.background = 'transparent';
                    }}
                >
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
        </div>
    );
}

Object.assign(window, { NewsTicker });