// Shared primitives for Survival landing page
// Stills, logo, navigation, labels

const { useState, useEffect, useRef } = React;

// -- Scroll reveal hook --
function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          el.classList.add('in');
          io.disconnect();
        }
      },
      { threshold: 0.12, rootMargin: '0px 0px -60px 0px' }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return ref;
}

// -- Reveal wrapper --
function Reveal({ children, delay = 0, as: Tag = 'div', style, className = '', ...rest }) {
  const ref = useReveal();
  return (
    <Tag
      ref={ref}
      className={`rev ${className}`}
      style={{ transitionDelay: `${delay}ms`, ...style }}
      {...rest}
    >
      {children}
    </Tag>
  );
}

// -- Still (photography or placeholder) --
// If `src` is provided, renders the image with a subtle caption overlay.
// Otherwise falls back to the striped film-still placeholder.
function Still({ caption, credit, aspect = '16 / 9', light = false, src, alt, position = 'center', style, children }) {
  return (
    <div
      className={`still ${light ? 'light' : ''} ${src ? 'has-image' : ''}`}
      style={{ aspectRatio: aspect, ...style }}
    >
      {src && (
        <img
          src={src}
          alt={alt || caption || ''}
          loading="lazy"
          style={{
            position: 'absolute', inset: 0,
            width: '100%', height: '100%',
            objectFit: 'cover',
            objectPosition: position,
            zIndex: 1,
          }}
        />
      )}
      {children}
      {(caption || credit) && (
        <div className="still-caption">
          <span>{caption}</span>
          {credit && <span>{credit}</span>}
        </div>
      )}
    </div>
  );
}

// -- Section header with running numbers --
function SectionHeader({ number, label, title, kicker, align = 'left' }) {
  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: 'auto 1fr',
      gap: '24px',
      alignItems: 'baseline',
      marginBottom: '56px',
    }}>
      <div className="label" style={{ minWidth: 80, paddingTop: 6 }}>
        <div>— {number}</div>
        <div style={{ marginTop: 6 }}>{label}</div>
      </div>
      <div>
        {kicker && (
          <div style={{
            fontFamily: 'var(--mono)',
            fontSize: 11,
            letterSpacing: '0.14em',
            textTransform: 'uppercase',
            color: 'var(--ember)',
            marginBottom: 16,
          }}>{kicker}</div>
        )}
        <h2 style={{
          fontFamily: 'var(--display)',
          fontWeight: 400,
          fontSize: 'clamp(34px, 4.8vw, 68px)',
          lineHeight: 1.05,
          letterSpacing: '-0.01em',
          color: 'var(--paper)',
          maxWidth: '18ch',
          textWrap: 'balance',
        }}>{title}</h2>
      </div>
    </div>
  );
}

// -- Wordmark --
function Wordmark({ size = 14, color, label }) {
  return (
    <div style={{
      fontFamily: 'var(--mono)',
      fontSize: size,
      letterSpacing: '0.32em',
      fontWeight: 500,
      color: color || 'var(--paper)',
      display: 'flex',
      alignItems: 'center',
      gap: 10,
    }}>
      <span style={{
        width: 6, height: 6,
        background: 'var(--ember)',
        display: 'inline-block',
      }} />
      {(label || 'CENTENNIAL').toUpperCase()}
    </div>
  );
}

// -- Navigation bar --
function Nav({ onInquire, filmTitle }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const items = [
    ['The Film', '#film'],
    ['Trailer', '#trailer'],
    ['The Team', '#team'],
    ['Production', '#production'],
    ['Opportunity', '#opportunity'],
  ];

  return (
    <nav style={{
      position: 'fixed',
      top: 0, left: 0, right: 0,
      zIndex: 100,
      padding: scrolled ? '14px 40px' : '22px 40px',
      transition: 'padding 300ms ease, background 300ms ease, border-color 300ms ease',
      background: scrolled ? 'rgba(11,15,20,0.78)' : 'transparent',
      backdropFilter: scrolled ? 'blur(18px) saturate(140%)' : 'none',
      WebkitBackdropFilter: scrolled ? 'blur(18px) saturate(140%)' : 'none',
      borderBottom: `1px solid ${scrolled ? 'var(--rule)' : 'transparent'}`,
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'space-between',
    }}>
      <Wordmark label={filmTitle} />
      <div style={{
        display: 'flex',
        alignItems: 'center',
        gap: 32,
        fontFamily: 'var(--mono)',
        fontSize: 11,
        letterSpacing: '0.14em',
        textTransform: 'uppercase',
        color: 'var(--mute)',
      }}>
        {items.map(([l, h]) => (
          <a key={h} href={h} style={{ transition: 'color 200ms' }}
             onMouseEnter={e => e.currentTarget.style.color = 'var(--paper)'}
             onMouseLeave={e => e.currentTarget.style.color = 'var(--mute)'}>
            {l}
          </a>
        ))}
        <button
          onClick={onInquire}
          style={{
            appearance: 'none', border: '1px solid var(--rule)',
            background: 'transparent', color: 'var(--paper)',
            fontFamily: 'var(--mono)', fontSize: 11,
            letterSpacing: '0.14em', textTransform: 'uppercase',
            padding: '10px 18px',
            cursor: 'pointer',
            transition: 'border-color 200ms, background 200ms, color 200ms',
          }}
          onMouseEnter={e => {
            e.currentTarget.style.borderColor = 'var(--ember)';
            e.currentTarget.style.color = 'var(--ember)';
          }}
          onMouseLeave={e => {
            e.currentTarget.style.borderColor = 'var(--rule)';
            e.currentTarget.style.color = 'var(--paper)';
          }}
        >
          Request the Deck
        </button>
      </div>
    </nav>
  );
}

// -- Container --
function Container({ children, style, narrow = false }) {
  return (
    <div style={{
      maxWidth: narrow ? 980 : 1360,
      margin: '0 auto',
      padding: '0 40px',
      ...style,
    }}>
      {children}
    </div>
  );
}

// -- Inquiry modal --
function InquiryModal({ open, onClose }) {
  const [sent, setSent] = useState(false);
  const [form, setForm] = useState({ name: '', org: '', email: '', role: 'Executive producer', note: '' });

  useEffect(() => {
    if (!open) { setSent(false); return; }
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [open, onClose]);

  if (!open) return null;

  const inputStyle = {
    width: '100%',
    background: 'transparent',
    border: 'none',
    borderBottom: '1px solid var(--rule)',
    color: 'var(--paper)',
    fontFamily: 'var(--ui)',
    fontSize: 15,
    padding: '12px 0',
    outline: 'none',
  };
  const labelStyle = {
    fontFamily: 'var(--mono)',
    fontSize: 10,
    letterSpacing: '0.18em',
    textTransform: 'uppercase',
    color: 'var(--mute)',
    marginBottom: 4,
    display: 'block',
  };

  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 200,
        background: 'rgba(11,15,20,0.82)',
        backdropFilter: 'blur(12px)',
        WebkitBackdropFilter: 'blur(12px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 40,
        animation: 'fadeIn 300ms ease',
      }}>
      <style>{`
        @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
        @keyframes slideUp { from { opacity: 0; transform: translateY(16px) } to { opacity: 1; transform: none } }
      `}</style>
      <div
        onClick={e => e.stopPropagation()}
        style={{
          width: '100%', maxWidth: 560,
          background: 'var(--ink-2)',
          border: '1px solid var(--rule)',
          padding: '48px 56px',
          animation: 'slideUp 400ms cubic-bezier(.2,.7,.2,1)',
          position: 'relative',
        }}>
        <button onClick={onClose} aria-label="Close"
          style={{
            position: 'absolute', top: 18, right: 18,
            appearance: 'none', background: 'transparent',
            border: 'none', color: 'var(--mute)',
            fontFamily: 'var(--mono)', fontSize: 12,
            cursor: 'pointer', padding: 8,
          }}>✕ CLOSE</button>

        {!sent ? (
          <>
            <div className="label" style={{ color: 'var(--ember)', marginBottom: 16 }}>— Private inquiry</div>
            <h3 style={{
              fontFamily: 'var(--display)',
              fontWeight: 400,
              fontSize: 38,
              lineHeight: 1.1,
              marginBottom: 10,
              letterSpacing: '-0.01em',
            }}>Request the investor deck</h3>
            <p style={{ color: 'var(--mute)', fontSize: 14, lineHeight: 1.6, marginBottom: 32 }}>
              A 24-page confidential deck — synopsis, sample reel access, budget summary,
              distribution strategy, and terms. We reply within 48 hours.
            </p>

            <div style={{ display: 'grid', gap: 20 }}>
              <div>
                <label style={labelStyle}>Name</label>
                <input style={inputStyle} value={form.name}
                  onChange={e => setForm({ ...form, name: e.target.value })}
                  placeholder="Your full name" />
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
                <div>
                  <label style={labelStyle}>Organization</label>
                  <input style={inputStyle} value={form.org}
                    onChange={e => setForm({ ...form, org: e.target.value })}
                    placeholder="Production co., fund, studio" />
                </div>
                <div>
                  <label style={labelStyle}>Email</label>
                  <input style={inputStyle} type="email" value={form.email}
                    onChange={e => setForm({ ...form, email: e.target.value })}
                    placeholder="you@company.com" />
                </div>
              </div>
              <div>
                <label style={labelStyle}>Role</label>
                <select style={{ ...inputStyle, appearance: 'none' }} value={form.role}
                  onChange={e => setForm({ ...form, role: e.target.value })}>
                  <option>Executive producer</option>
                  <option>Producer</option>
                  <option>Investor / financier</option>
                  <option>Distribution / acquisitions</option>
                  <option>Foundation / grant-maker</option>
                  <option>Other</option>
                </select>
              </div>
              <div>
                <label style={labelStyle}>Note (optional)</label>
                <textarea style={{ ...inputStyle, minHeight: 60, resize: 'vertical', fontFamily: 'var(--ui)' }}
                  value={form.note}
                  onChange={e => setForm({ ...form, note: e.target.value })}
                  placeholder="Anything we should know" />
              </div>
            </div>

            <button
              onClick={() => setSent(true)}
              style={{
                marginTop: 36,
                appearance: 'none', border: 'none',
                background: 'var(--ember)', color: 'var(--ink)',
                fontFamily: 'var(--mono)', fontSize: 12,
                letterSpacing: '0.18em', textTransform: 'uppercase',
                fontWeight: 600,
                padding: '16px 28px',
                cursor: 'pointer',
                width: '100%',
              }}>
              Send request →
            </button>
          </>
        ) : (
          <div style={{ textAlign: 'center', padding: '24px 0' }}>
            <div className="label" style={{ color: 'var(--ember)', marginBottom: 16 }}>— Sent</div>
            <h3 style={{
              fontFamily: 'var(--display)', fontWeight: 400,
              fontSize: 34, lineHeight: 1.15, marginBottom: 14,
            }}>Thank you.</h3>
            <p style={{ color: 'var(--mute)', fontSize: 14, lineHeight: 1.6, maxWidth: 380, margin: '0 auto' }}>
              We'll be in touch within 48 hours with the confidential deck and a link to the sizzle reel.
            </p>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, {
  useReveal, Reveal, Still, SectionHeader,
  Wordmark, Nav, Container, InquiryModal,
});
