// Shared presentational components + app shell chrome for the NLC app.
// All visuals use design-system tokens (var(--nl-*)) and .nl-* utility classes.
(function () {
  const { Icon } = window;
  // Real device insets (status bar / dynamic island, home indicator).
  // env() resolves to 0 in a plain browser tab, so screens still get a small top pad.
  const safeTop = (extra = 8) => `calc(env(safe-area-inset-top, 0px) + ${extra}px)`;
  const safeBottom = (extra = 10) => `calc(env(safe-area-inset-bottom, 0px) + ${extra}px)`;

  // ---- theme palettes for series / gallery / event art --------------------
  function art(theme) {
    switch (theme) {
      case 'leaf':  return { bg: 'linear-gradient(150deg, var(--nl-leaf-700), var(--nl-leaf-900))', fg: '#fff', eye: 'rgba(255,255,255,0.82)', motif: 'rgba(255,255,255,0.10)' };
      case 'wheat': return { bg: 'linear-gradient(150deg, var(--nl-wheat-500), var(--nl-wheat-700))', fg: 'var(--nl-navy-900)', eye: 'var(--nl-navy-800)', motif: 'rgba(8,54,77,0.10)' };
      case 'clay':  return { bg: 'linear-gradient(150deg, var(--nl-clay-500), var(--nl-clay-700))', fg: '#fff', eye: 'rgba(255,255,255,0.85)', motif: 'rgba(255,255,255,0.12)' };
      default:      return { bg: 'linear-gradient(155deg, var(--nl-navy-700), var(--nl-navy-900))', fg: '#fff', eye: 'var(--nl-leaf-500)', motif: 'rgba(145,202,65,0.16)' };
    }
  }

  // Typographic series / media art — the brand's "type as imagery" mode.
  function SeriesArt({ theme = 'navy', title, kicker, sub, radius = 16, style = {}, children, compact }) {
    const t = art(theme);
    return (
      <div style={{
        position: 'relative', overflow: 'hidden', borderRadius: radius,
        background: t.bg, color: t.fg, width: '100%', height: '100%',
        display: 'flex', flexDirection: 'column', justifyContent: 'flex-end',
        padding: compact ? 14 : 18, boxSizing: 'border-box', ...style,
      }}>
        {/* faint oversized quote motif — never the leaf */}
        <div style={{
          position: 'absolute', top: compact ? -22 : -30, right: -6, lineHeight: 1,
          fontFamily: 'var(--nl-font-serif)', fontWeight: 700,
          fontSize: compact ? 120 : 168, color: t.motif, userSelect: 'none',
        }}>”</div>
        {kicker && <div style={{
          fontFamily: 'var(--nl-font-sans)', fontWeight: 700, fontSize: 10.5,
          letterSpacing: '0.18em', textTransform: 'uppercase', color: t.eye,
          marginBottom: 6,
        }}>{kicker}</div>}
        <div style={{
          fontFamily: 'var(--nl-font-serif)', fontWeight: 600,
          fontSize: compact ? 19 : 26, lineHeight: 1.05, letterSpacing: '-0.01em',
          textWrap: 'balance',
        }}>{title}</div>
        {sub && <div style={{
          fontFamily: 'var(--nl-font-sans)', fontSize: 12.5, marginTop: 6,
          color: t.fg, opacity: 0.8,
        }}>{sub}</div>}
        {children}
      </div>
    );
  }

  // ---- eyebrow / section header -------------------------------------------
  function Eyebrow({ children, color = 'var(--nl-leaf-700)', style }) {
    return <div className="nl-eyebrow" style={{ color, ...style }}>{children}</div>;
  }

  function SectionHeader({ title, action, onAction, style }) {
    return (
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
        padding: '0 20px', marginBottom: 14, ...style }}>
        <h2 style={{ fontFamily: 'var(--nl-font-serif)', fontWeight: 600, fontSize: 22,
          letterSpacing: '-0.01em', color: 'var(--nl-navy-900)', margin: 0, whiteSpace: 'nowrap',
          flex: 1, minWidth: 0 }}>{title}</h2>
        {action && <button onClick={onAction} style={{
          background: 'none', border: 0, cursor: 'pointer', padding: 0, flexShrink: 0,
          fontFamily: 'var(--nl-font-sans)', fontWeight: 600, fontSize: 14, whiteSpace: 'nowrap',
          color: 'var(--nl-leaf-700)', display: 'flex', alignItems: 'center', gap: 2,
        }}>{action}<Icon name="chevronRight" size={15} strokeWidth={2.2} /></button>}
      </div>
    );
  }

  // ---- glass icon button (top bar) ----------------------------------------
  function RoundBtn({ name, onClick, badge, color = 'var(--nl-navy-800)', bg = 'var(--nl-white)', size = 38 }) {
    return (
      <button onClick={onClick} style={{
        width: size, height: size, borderRadius: 999, border: '1px solid var(--nl-border)',
        background: bg, color, cursor: 'pointer', position: 'relative',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        boxShadow: 'var(--nl-shadow-sm)', flexShrink: 0,
      }}>
        <Icon name={name} size={20} strokeWidth={1.7} />
        {badge && <span style={{ position: 'absolute', top: 6, right: 6, width: 8, height: 8,
          borderRadius: 999, background: 'var(--nl-clay-500)', border: '1.5px solid var(--nl-white)' }} />}
      </button>
    );
  }

  // ---- app header (custom, brand) -----------------------------------------
  // variant: 'home' (logo + actions), 'large' (big serif title), 'detail' (back + title)
  function AppHeader({ variant = 'large', title, onBack, right, scrolled }) {
    const base = {
      paddingTop: safeTop(8), position: 'sticky', top: 0, zIndex: 30,
      background: scrolled ? 'rgba(251,250,246,0.86)' : 'var(--nl-bg)',
      backdropFilter: scrolled ? 'saturate(180%) blur(14px)' : 'none',
      WebkitBackdropFilter: scrolled ? 'saturate(180%) blur(14px)' : 'none',
      borderBottom: scrolled ? '1px solid var(--nl-border)' : '1px solid transparent',
      transition: 'background .2s, border-color .2s',
    };
    if (variant === 'detail') {
      return (
        <div style={{ ...base }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 16px 12px' }}>
            <RoundBtn name="chevronLeft" onClick={onBack} />
            <div style={{ flex: 1, fontFamily: 'var(--nl-font-sans)', fontWeight: 600,
              fontSize: 16, color: 'var(--nl-navy-900)', textAlign: 'center',
              opacity: scrolled ? 1 : 0, transition: 'opacity .2s',
              whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{title}</div>
            <div style={{ display: 'flex', gap: 8 }}>{right || <div style={{ width: 38 }} />}</div>
          </div>
        </div>
      );
    }
    if (variant === 'home') {
      return (
        <div style={{ ...base }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '4px 18px 12px' }}>
            <img src="assets/logo-color.png" alt="New Life Church" style={{ height: 30 }} />
            <div style={{ display: 'flex', gap: 8 }}>{right}</div>
          </div>
        </div>
      );
    }
    // large
    return (
      <div style={{ ...base }}>
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between',
          padding: '4px 20px 10px' }}>
          <h1 style={{ fontFamily: 'var(--nl-font-serif)', fontWeight: 600, fontSize: 32,
            letterSpacing: '-0.02em', color: 'var(--nl-navy-900)', margin: 0, whiteSpace: 'nowrap' }}>{title}</h1>
          <div style={{ display: 'flex', gap: 8, paddingBottom: 4 }}>{right}</div>
        </div>
      </div>
    );
  }

  // ---- bottom tab bar ------------------------------------------------------
  const TABS = [
    { id: 'home', label: 'Home', icon: 'home' },
    { id: 'watch', label: 'Watch', icon: 'play' },
    { id: 'bible', label: 'Bible', icon: 'bookOpen' },
    { id: 'give', label: 'Give', icon: 'heart' },
    { id: 'more', label: 'More', icon: 'grid' },
  ];
  function TabBar({ active, onChange }) {
    return (
      <div style={{
        flexShrink: 0, background: 'rgba(251,250,246,0.92)',
        backdropFilter: 'saturate(180%) blur(16px)', WebkitBackdropFilter: 'saturate(180%) blur(16px)',
        borderTop: '1px solid var(--nl-border)', paddingBottom: safeBottom(10),
        display: 'flex', justifyContent: 'space-around', alignItems: 'center',
        position: 'relative', zIndex: 40,
      }}>
        {TABS.map(t => {
          const on = active === t.id;
          return (
            <button key={t.id} onClick={() => onChange(t.id)} style={{
              flex: 1, background: 'none', border: 0, cursor: 'pointer',
              padding: '10px 0 6px', display: 'flex', flexDirection: 'column',
              alignItems: 'center', gap: 3,
              color: on ? 'var(--nl-navy-800)' : 'var(--nl-ink-400)',
            }}>
              <Icon name={t.icon} size={24} strokeWidth={on ? 2.1 : 1.7}
                fill={on ? 'currentColor' : 'none'} />
              <span style={{ fontFamily: 'var(--nl-font-sans)', fontSize: 10.5,
                fontWeight: on ? 700 : 500, letterSpacing: '0.01em' }}>{t.label}</span>
            </button>
          );
        })}
      </div>
    );
  }

  // ---- badge / chip --------------------------------------------------------
  function Chip({ children, tone = 'leaf', solid, style }) {
    const cls = 'nl-badge' + (tone === 'navy' ? ' nl-badge--navy' : tone === 'clay' ? ' nl-badge--clay'
      : tone === 'wheat' ? ' nl-badge--wheat' : solid ? ' nl-badge--solid' : '');
    return <span className={cls} style={style}>{children}</span>;
  }

  // ---- progress bar --------------------------------------------------------
  function Progress({ value, color = 'var(--nl-leaf-600)' }) {
    return (
      <div style={{ height: 3, borderRadius: 999, background: 'var(--nl-ink-200)', overflow: 'hidden' }}>
        <div style={{ height: '100%', width: `${Math.round(value * 100)}%`, background: color, borderRadius: 999 }} />
      </div>
    );
  }

  // ---- scroll-aware screen scaffold ---------------------------------------
  function Screen({ header, children, pad = true, bg = 'var(--nl-bg)', noTabPad }) {
    const [scrolled, setScrolled] = React.useState(false);
    return (
      <div onScroll={e => setScrolled(e.target.scrollTop > 4)}
        style={{ height: '100%', overflowY: 'auto', overflowX: 'hidden', background: bg,
          WebkitOverflowScrolling: 'touch' }}>
        {header && <AppHeader {...header} scrolled={scrolled} />}
        <div style={{ paddingBottom: noTabPad ? 0 : 28 }}>{children}</div>
      </div>
    );
  }

  window.NLUI = { safeTop, safeBottom, art, SeriesArt, Eyebrow, SectionHeader,
    RoundBtn, AppHeader, TabBar, TABS, Chip, Progress, Screen };
})();
