/* global React, firebase */

// ── Design tokens ──────────────────────────────────────────────────────────
const C = {
  bg:       '#0B0C0E',
  bg1:      '#141518',
  bone:     '#E6DCCB',
  grey:     '#8A8A86',
  mute:     '#52524F',
  border:   '#1F2024',
  borderHi: '#33353A',
  cyan:     '#59A3B3',
};

const F = {
  display: "'Playfair Display', Georgia, serif",
  sans:    "'IBM Plex Sans', system-ui, sans-serif",
  mono:    "'IBM Plex Mono', monospace",
};

const ease = 'cubic-bezier(0.2,0.7,0.2,1)';
const wrap = { width: 'min(1080px, calc(100% - 48px))', margin: '0 auto' };

// ── Viewfinder corner bracket ───────────────────────────────────────────────
function Corner({ top, right, bottom, left }) {
  const color = 'rgba(89,163,179,0.5)';
  const t = 1;
  return (
    <div style={{
      position: 'absolute',
      width: 16, height: 16,
      top, right, bottom, left,
      borderColor: color,
      borderStyle: 'solid',
      borderWidth: 0,
      borderTopWidth:    top    !== undefined ? t : 0,
      borderBottomWidth: bottom !== undefined ? t : 0,
      borderLeftWidth:   left   !== undefined ? t : 0,
      borderRightWidth:  right  !== undefined ? t : 0,
    }} />
  );
}

// ── Showgaze mark (Kenaz, flipped to face right) ───────────────────────────
function Mark({ size = 20, animate = false }) {
  return (
    <img
      src="assets/logo/mark-cream-512.png"
      alt="Showgaze mark"
      style={{
        width: size * 1.8,
        height: size,
        objectFit: 'contain',
        objectPosition: 'left center',
        display: 'block',
        // When animate=true, the 'breathe' keyframe owns the transform (includes scaleX(-1))
        transform: animate ? undefined : 'scaleX(-1)',
        animation: animate ? 'breathe 6s ease-in-out infinite' : 'none',
        transformOrigin: 'center',
      }}
    />
  );
}

// ── Header ─────────────────────────────────────────────────────────────────
function Header() {
  return (
    <header className="anim-0" style={{
      position: 'sticky',
      top: 0,
      zIndex: 10,
      background: 'rgba(11,12,14,0.90)',
      backdropFilter: 'blur(18px)',
      WebkitBackdropFilter: 'blur(18px)',
      borderBottom: `1px solid ${C.border}`,
    }}>
      <div style={{
        ...wrap,
        height: 56,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
      }}>
        <a href="#" style={{ display: 'flex', alignItems: 'center', gap: 10, textDecoration: 'none' }}>
          <Mark size={20} animate />
          <span style={{ fontFamily: F.display, fontSize: 18, color: C.bone, letterSpacing: '0.01em' }}>
            showgaze
          </span>
        </a>
        <div style={{ display: 'flex', alignItems: 'center', gap: 20 }}>

          {/* Status indicator */}
          <div style={{
            display: 'flex',
            alignItems: 'center',
            gap: 7,
            fontFamily: F.mono,
            fontSize: 9,
            letterSpacing: '0.2em',
            textTransform: 'uppercase',
            color: C.mute,
          }}>
            <span style={{
              width: 5, height: 5,
              borderRadius: '50%',
              background: C.cyan,
              opacity: 0.55,
              display: 'inline-block',
              flexShrink: 0,
            }} />
            App in development
          </div>

          {/* Organizer login */}
          <a
            href="/apply/login"
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: 6,
              fontFamily: F.mono,
              fontSize: 9,
              letterSpacing: '0.18em',
              textTransform: 'uppercase',
              textDecoration: 'none',
              color: C.grey,
              border: `1px solid ${C.border}`,
              borderRadius: 4,
              padding: '6px 12px',
              transition: `all 160ms ${ease}`,
            }}
            onMouseEnter={e => {
              e.currentTarget.style.borderColor = C.borderHi;
              e.currentTarget.style.color = C.bone;
            }}
            onMouseLeave={e => {
              e.currentTarget.style.borderColor = C.border;
              e.currentTarget.style.color = C.grey;
            }}
          >
            {/* Lock icon inline SVG */}
            <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}>
              <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
              <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
            </svg>
            Organizer Login
          </a>

        </div>
      </div>
    </header>
  );
}

// ── Kenaz mark — draws on load, rune pivots around circle on scroll ────────
function KenazMark({ size = 80 }) {
  const pathRef = React.useRef(null);

  React.useEffect(() => {
    function tick() {
      if (!pathRef.current) return;
      const angle = window.scrollY * 0.10;
      pathRef.current.setAttribute('transform', `rotate(${angle}, 700, 512)`);
    }
    window.addEventListener('scroll', tick, { passive: true });
    return () => window.removeEventListener('scroll', tick);
  }, []);

  return (
    <svg
      viewBox="0 0 1024 1024"
      width={size}
      height={size}
      aria-hidden="true"
      style={{ display: 'block', overflow: 'visible' }}
    >
      <g fill="none" stroke="#E6DCCB" strokeLinecap="butt" strokeLinejoin="miter">
        {/* Path draws first, then circle closes around it */}
        <path
          ref={pathRef}
          d="M492 318 L304 512 L492 706"
          strokeWidth="76"
          style={{
            strokeDasharray: 545,
            animation: 'drawPath 0.55s cubic-bezier(0.4,0,0.2,1) 0.15s both',
          }}
        />
        <circle
          cx="700" cy="512" r="108"
          strokeWidth="56"
          style={{
            strokeDasharray: 685,
            animation: 'drawCircle 0.6s cubic-bezier(0.4,0,0.2,1) 0.5s both',
          }}
        />
      </g>
    </svg>
  );
}

// ── Hero CTA — links to the intake form ────────────────────────────────────
function HeroForm() {
  return (
    <div className="anim-5" style={{
      flex: '1 1 240px',
      maxWidth: 320,
      paddingLeft: 48,
      borderLeft: '1px solid rgba(255,255,255,0.07)',
      display: 'flex',
      flexDirection: 'column',
      justifyContent: 'center',
    }}>
      <p style={{
        margin: '0 0 16px',
        fontFamily: F.display,
        fontSize: 'clamp(20px, 2vw, 26px)',
        color: C.bone,
        lineHeight: 1.1,
      }}>
        Ready to start?
      </p>

      <a
        href="/apply/"
        style={{
          display: 'block',
          width: '100%',
          textAlign: 'center',
          textDecoration: 'none',
          fontFamily: F.mono,
          fontSize: 10,
          letterSpacing: '0.18em',
          textTransform: 'uppercase',
          background: C.cyan,
          color: '#0B0C0E',
          border: `1px solid ${C.cyan}`,
          borderRadius: 4,
          padding: '12px 0',
          cursor: 'pointer',
          transition: `all 180ms ${ease}`,
          marginBottom: 10,
        }}
        onMouseEnter={e => {
          e.currentTarget.style.background = 'transparent';
          e.currentTarget.style.color = C.cyan;
        }}
        onMouseLeave={e => {
          e.currentTarget.style.background = C.cyan;
          e.currentTarget.style.color = '#0B0C0E';
        }}
      >
        Apply Now
      </a>

      <a
        href="mailto:hello@showgaze.app"
        style={{
          display: 'block',
          width: '100%',
          textAlign: 'center',
          textDecoration: 'none',
          fontFamily: F.mono,
          fontSize: 10,
          letterSpacing: '0.18em',
          textTransform: 'uppercase',
          background: 'transparent',
          color: C.grey,
          border: `1px solid ${C.border}`,
          borderRadius: 4,
          padding: '11px 0',
          cursor: 'pointer',
          transition: `all 180ms ${ease}`,
          marginBottom: 14,
        }}
        onMouseEnter={e => {
          e.currentTarget.style.borderColor = C.borderHi;
          e.currentTarget.style.color = C.bone;
        }}
        onMouseLeave={e => {
          e.currentTarget.style.borderColor = C.border;
          e.currentTarget.style.color = C.grey;
        }}
      >
        Want to know more?
      </a>

      <p style={{ margin: 0, fontFamily: F.mono, fontSize: 9, letterSpacing: '0.06em', color: C.mute }}>
        hello@showgaze.app
      </p>
    </div>
  );
}

// ── Hero — text over photograph ────────────────────────────────────────────
function Hero() {
  const imgRef = React.useRef(null);

  React.useEffect(() => {
    function tick() {
      if (!imgRef.current) return;
      imgRef.current.style.transform = `translateY(${window.scrollY * 0.22}px)`;
    }
    window.addEventListener('scroll', tick, { passive: true });
    return () => window.removeEventListener('scroll', tick);
  }, []);

  return (
    <section style={{
      position: 'relative',
      height: 'calc(100vh - 56px)',
      minHeight: 540,
      maxHeight: 920,
      overflow: 'hidden',
      display: 'flex',
      flexDirection: 'column',
      justifyContent: 'flex-end',
    }}>
      {/* Photograph — slightly oversized for parallax headroom */}
      <img
        ref={imgRef}
        src="assets/images/crowd_filming_cinematic.png"
        alt=""
        aria-hidden="true"
        style={{
          position: 'absolute',
          top: '-8%',
          left: 0,
          width: '100%',
          height: '116%',
          objectFit: 'cover',
          objectPosition: 'center 22%',
          willChange: 'transform',
        }}
      />

      {/* Gradient — darkens bottom so text reads clean */}
      <div style={{
        position: 'absolute',
        inset: 0,
        background: [
          `linear-gradient(to top, ${C.bg} 0%, rgba(11,12,14,0.72) 28%, rgba(11,12,14,0.1) 60%)`,
          `linear-gradient(to right, rgba(11,12,14,0.55) 0%, transparent 70%)`,
        ].join(', '),
        pointerEvents: 'none',
      }} />

      {/* Viewfinder corner marks */}
      <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
        <Corner top={18} left={22} />
        <Corner top={18} right={22} />
        <Corner bottom={18} left={22} />
        <Corner bottom={18} right={22} />
      </div>

      {/* Slow scanline sweep */}
      <div style={{
        position: 'absolute',
        left: 0, right: 0,
        height: 1,
        background: `linear-gradient(90deg, transparent, ${C.cyan}44, transparent)`,
        animation: 'scanline 9s ease-in-out infinite',
        pointerEvents: 'none',
      }} />

      {/* Text — two-column, bottom-anchored */}
      <div style={{
        position: 'relative', zIndex: 1,
        ...wrap, paddingBottom: 64,
        display: 'flex',
        alignItems: 'flex-end',
        gap: '40px 72px',
        flexWrap: 'wrap',
      }}>

        {/* Left — branding + headline */}
        <div style={{ flex: '3 1 320px' }}>

          {/* Logo lockup */}
          <div className="anim-1" style={{
            display: 'flex',
            alignItems: 'center',
            gap: 18,
            marginBottom: 28,
          }}>
            <KenazMark size={80} />
            <span style={{
              fontFamily: F.display,
              fontSize: 26,
              fontWeight: 600,
              color: C.bone,
              letterSpacing: '0.08em',
              lineHeight: 1,
            }}>
              SHOWGAZE
            </span>
          </div>

          <p className="anim-2" style={{
            margin: '0 0 12px',
            fontFamily: F.display,
            fontSize: 'clamp(28px, 4.2vw, 56px)',
            lineHeight: 1.08,
            letterSpacing: '-0.01em',
            color: C.bone,
          }}>
            Well... You've got all these people filming anyway.
          </p>

          <p className="anim-3" style={{
            margin: '0 0 20px',
            fontFamily: F.mono,
            fontSize: 'clamp(11px, 1vw, 14px)',
            letterSpacing: '0.18em',
            color: C.bone,
            opacity: 0.45,
          }}>
            Sync. Cut. Post.
          </p>

          <p className="anim-4" style={{
            margin: 0,
            fontFamily: F.sans,
            fontSize: 'clamp(12px, 1.2vw, 14px)',
            lineHeight: 1.75,
            color: 'rgba(230,220,203,0.55)',
            maxWidth: 440,
          }}>
            A tool for live event producers — festival teams, venue operators, and
            anyone who wants to do something with the clips fans are already shooting.
          </p>
        </div>

        {/* Right — compact contact form */}
        <HeroForm />

      </div>
    </section>
  );
}

// ── Two-column info ────────────────────────────────────────────────────────
function Kicker({ children }) {
  return (
    <div style={{
      fontFamily: F.mono,
      fontSize: 9,
      letterSpacing: '0.22em',
      textTransform: 'uppercase',
      color: C.cyan,
      marginBottom: 18,
    }}>
      {children}
    </div>
  );
}

function InfoRow() {
  return (
    <div className="anim-6" style={{
      ...wrap,
      padding: '80px 0 84px',
      display: 'grid',
      gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))',
      gap: '52px 96px',
      borderBottom: `1px solid ${C.border}`,
    }}>
      <div>
        <Kicker>Who it's for</Kicker>
        <p style={{ margin: 0, fontFamily: F.sans, fontSize: 15, lineHeight: 1.72, color: C.grey }}>
          Event producers and post-production teams who want to capture what the
          crowd sees, without adding complexity to the night itself.
        </p>
      </div>
      <div>
        <Kicker>How it works today</Kicker>
        <p style={{ margin: 0, fontFamily: F.sans, fontSize: 15, lineHeight: 1.72, color: C.grey }}>
          Fans contribute through a simple web link — no install required.
          A dedicated fan app is in development. For producers, everything
          arrives in one organised view after the event.
        </p>
      </div>
    </div>
  );
}

// ── Contact form → Firestore ───────────────────────────────────────────────
function ContactForm() {
  const [email,   setEmail]   = React.useState('');
  const [message, setMessage] = React.useState('');
  const [status,  setStatus]  = React.useState('idle');
  // status: 'idle' | 'loading' | 'success' | 'fallback'

  async function handleSubmit(e) {
    e.preventDefault();
    setStatus('loading');
    try {
      if (!window.db) throw new Error('Firestore not configured');
      await window.db.collection('intake_submissions').add({
        email:     email.trim(),
        message:   message.trim() || null,
        source:    'showgaze.app',
        timestamp: firebase.firestore.FieldValue.serverTimestamp(),
      });
      setStatus('success');
    } catch (_err) {
      // Firebase not wired up yet — fall back to mailto
      const body = [message.trim(), `\n— ${email.trim()}`].filter(Boolean).join('\n');
      window.location.href =
        `mailto:hello@showgaze.app?subject=${encodeURIComponent('Showgaze enquiry')}&body=${encodeURIComponent(body)}`;
      setStatus('fallback');
    }
  }

  const btnBase = {
    fontFamily: F.mono,
    fontSize: 10,
    letterSpacing: '0.18em',
    textTransform: 'uppercase',
    background: 'transparent',
    borderRadius: 4,
    padding: '12px 28px',
    cursor: 'pointer',
    transition: `all 180ms ${ease}`,
  };

  return (
    <div className="anim-5" style={{ ...wrap, padding: '88px 0 104px' }}>
      <p style={{
        margin: '0 0 44px',
        fontFamily: F.display,
        fontSize: 'clamp(26px, 3.6vw, 44px)',
        lineHeight: 1.1,
        color: C.bone,
        maxWidth: 480,
      }}>
        Get in touch.
      </p>

      {status === 'success' ? (
        <p style={{
          margin: 0,
          fontFamily: F.mono,
          fontSize: 11,
          letterSpacing: '0.14em',
          textTransform: 'uppercase',
          color: '#6FB89B',
        }}>
          Thanks — we'll be in touch soon.
        </p>
      ) : (
        <form onSubmit={handleSubmit} style={{ maxWidth: 480 }}>
          <input
            type="email"
            required
            value={email}
            onChange={e => setEmail(e.target.value)}
            placeholder="your@email.com"
            style={{
              display: 'block',
              width: '100%',
              padding: '13px 14px',
              fontSize: 13,
              marginBottom: 10,
              borderRadius: 4,
            }}
          />
          <textarea
            value={message}
            onChange={e => setMessage(e.target.value)}
            placeholder="Tell us about your event — or just say hello. (optional)"
            rows={3}
            style={{
              display: 'block',
              width: '100%',
              padding: '13px 14px',
              fontSize: 13,
              resize: 'vertical',
              marginBottom: 14,
              lineHeight: 1.55,
              borderRadius: 4,
            }}
          />
          <button
            type="submit"
            disabled={status === 'loading'}
            style={{
              ...btnBase,
              color:       status === 'loading' ? C.mute : C.bone,
              borderColor: status === 'loading' ? C.border : C.borderHi,
              borderWidth: 1,
              borderStyle: 'solid',
            }}
            onMouseEnter={e => {
              if (status !== 'loading') {
                e.currentTarget.style.borderColor = C.cyan;
                e.currentTarget.style.color = C.cyan;
              }
            }}
            onMouseLeave={e => {
              if (status !== 'loading') {
                e.currentTarget.style.borderColor = C.borderHi;
                e.currentTarget.style.color = C.bone;
              }
            }}
          >
            {status === 'loading' ? 'Sending…' : 'Send'}
          </button>

          <p style={{
            margin: '22px 0 0',
            fontFamily: F.mono,
            fontSize: 10,
            letterSpacing: '0.06em',
            color: C.mute,
          }}>
            Or reach us directly:{' '}
            <a
              href="mailto:hello@showgaze.app"
              style={{ color: C.grey, textDecoration: 'none', transition: `color 140ms ${ease}` }}
              onMouseEnter={e => e.currentTarget.style.color = C.bone}
              onMouseLeave={e => e.currentTarget.style.color = C.grey}
            >
              hello@showgaze.app
            </a>
          </p>
        </form>
      )}
    </div>
  );
}

// ── Footer ─────────────────────────────────────────────────────────────────
function Footer() {
  return (
    <footer style={{ borderTop: `1px solid ${C.border}` }}>
      <div style={{
        ...wrap,
        padding: '22px 0 28px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        flexWrap: 'wrap',
        gap: 12,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
          <Mark size={15} />
          <span style={{ fontFamily: F.display, fontSize: 15, color: C.bone }}>showgaze</span>
        </div>
        <span style={{
          fontFamily: F.mono,
          fontSize: 9,
          letterSpacing: '0.16em',
          textTransform: 'uppercase',
          color: C.mute,
        }}>
          © 2026 Showgaze
        </span>
      </div>
    </footer>
  );
}

// ── Root ───────────────────────────────────────────────────────────────────
function PromoSite() {
  return (
    <div style={{ background: C.bg, color: C.bone, minHeight: '100vh' }}>
      <Header />
      <main>
        <Hero />
        <InfoRow />
      </main>
      <Footer />
    </div>
  );
}

window.PromoSite = PromoSite;
