// Shared: LandingNav, Hero body (without background), Particles

// Cross-script scope bridge: Babel scripts don't share variables.
const HeroMonitor = window.HeroMonitor
const HeroPhone = window.HeroPhone

const Particles = ({ count = 42 }) => {
  const particles = React.useMemo(
    () =>
      Array.from({ length: count }).map(() => ({
        x: Math.random() * 100,
        size: 1 + Math.random() * 2,
        dur: 12 + Math.random() * 16,
        delay: Math.random() * 20,
        opacity: 0.3 + Math.random() * 0.5,
      })),
    [count],
  )
  return (
    <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
      {particles.map((p, i) => (
        <div
          key={i}
          style={{
            position: 'absolute',
            left: `${p.x}%`,
            bottom: '-4px',
            width: p.size,
            height: p.size,
            borderRadius: 9999,
            background: '#ffffff',
            opacity: p.opacity,
            boxShadow: '0 0 10px rgba(255,255,255,0.9)',
            animation: `sp-float-up ${p.dur}s linear infinite`,
            animationDelay: `${p.delay}s`,
          }}
        />
      ))}
    </div>
  )
}

// Background STACK (cobalt + orange + cyan + grid + particles) - NO fade layer
// Each variant composes its own transition on top
const BackgroundStack = ({ children }) => (
  <div
    aria-hidden
    style={{ position: 'absolute', inset: 0, overflow: 'hidden', pointerEvents: 'none' }}
  >
    <div
      style={{
        position: 'absolute',
        inset: 0,
        background:
          'radial-gradient(ellipse 70% 100% at 50% 0%, rgba(60,120,220,0.35) 0%, rgba(60,120,220,0.10) 30%, transparent 65%)',
      }}
    />
    <div
      style={{
        position: 'absolute',
        inset: 0,
        background:
          'radial-gradient(ellipse 38% 55% at 25% 60%, rgba(255,107,0,0.60) 0%, rgba(255,107,0,0.18) 35%, transparent 70%)',
      }}
    />
    <div
      style={{
        position: 'absolute',
        inset: 0,
        background:
          'radial-gradient(ellipse 38% 55% at 75% 60%, rgba(93,230,255,0.55) 0%, rgba(93,230,255,0.16) 35%, transparent 70%)',
      }}
    />
    <div
      style={{
        position: 'absolute',
        inset: 0,
        backgroundImage:
          'linear-gradient(rgba(93,230,255,0.18) 1px, transparent 1px), linear-gradient(90deg, rgba(93,230,255,0.18) 1px, transparent 1px)',
        backgroundSize: '72px 72px',
        opacity: 0.25,
        WebkitMaskImage:
          'radial-gradient(ellipse 80% 60% at 50% 40%, black 0%, black 40%, transparent 90%)',
        maskImage:
          'radial-gradient(ellipse 80% 60% at 50% 40%, black 0%, black 40%, transparent 90%)',
      }}
    />
    <Particles count={42} />
    {children}
  </div>
)

const NAV_ITEMS = [
  { label: 'Özellikler', target: 'intro' },
  { label: 'Pazaryerleri', target: 'unified' },
  { label: 'Fiyatlandırma', target: 'pricing' },
]

const MOBILE_BREAKPOINT = 768 // Below this: hamburger menu

const LandingNav = () => {
  const [scrolled, setScrolled] = React.useState(false)
  const [isMobile, setIsMobile] = React.useState(
    typeof window !== 'undefined' && window.innerWidth < MOBILE_BREAKPOINT,
  )
  // Scroll-event detection (replaces IntersectionObserver which had an iOS
  // Safari bug: sentinel at top:0 + rootMargin -60px meant NOT-intersecting
  // from the start, so scrolled was permanently true → header never transparent).
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20)
    onScroll()
    window.addEventListener('scroll', onScroll, { passive: true })
    return () => window.removeEventListener('scroll', onScroll)
  }, [])

  // Viewport width tracker — mobile detection
  React.useEffect(() => {
    const onResize = () => setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
    onResize()
    window.addEventListener('resize', onResize)
    return () => window.removeEventListener('resize', onResize)
  }, [])

  const scrollTo = (target) => {
    const el = document.getElementById(target)
    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'center' })
  }

  // Navigate PARENT window (escapes iframe). Same-origin so allowed.
  const goTo = (path) => {
    try {
      window.top.location.href = path
    } catch {
      window.location.href = path
    }
  }

  // Logo click: back to landing root (scroll-top + reload effect)
  const onLogoClick = () => goTo('/')
  // Primary CTA click: waitlist
  const onStartClick = () => goTo('/waitlist')
  // Login link (added 2026-05-04 — fix for "no visible way back to dashboard
  // after cookie expires"). Routes/index.tsx now also auto-revives via
  // refreshSession(); this link is the visible fallback for the 5% where
  // the refresh-token is also dead.
  const onLoginClick = () => goTo('/login')

  return (
    <React.Fragment>
      <nav
        style={{
          position: scrolled ? 'fixed' : 'absolute',
          top: 0,
          left: 0,
          right: 0,
          zIndex: 50,
          background: scrolled ? 'rgba(19,19,21,0.85)' : 'transparent',
          backdropFilter: scrolled ? 'blur(18px)' : 'none',
          WebkitBackdropFilter: scrolled ? 'blur(18px)' : 'none',
          borderBottom: scrolled ? '1px solid rgba(255,255,255,0.04)' : '1px solid transparent',
          boxShadow: scrolled ? '0 20px 40px rgba(0,0,0,0.4)' : 'none',
          transition:
            'background .4s ease, backdrop-filter .4s ease, border-color .4s ease, box-shadow .4s ease',
        }}
      >
        <div
          style={{
            maxWidth: 1280,
            margin: '0 auto',
            padding: isMobile ? '12px 18px' : '14px 32px',
            display: 'flex',
            alignItems: 'center',
            gap: isMobile ? 12 : 24,
            justifyContent: isMobile ? 'space-between' : 'flex-start',
          }}
        >
          {/* Logo — clickable, goes to '/' (root, which reloads and scrolls top) */}
          <div
            onClick={onLogoClick}
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: 10,
              flexShrink: 0,
              cursor: 'pointer',
            }}
          >
            <img
              src="assets/shoppanel-logo.png"
              alt="ShopPanel"
              style={{
                width: 32,
                height: 32,
                borderRadius: 7,
                display: 'block',
                objectFit: 'cover',
                boxShadow: '0 0 18px rgba(255,107,0,0.35)',
              }}
            />
            <div
              style={{
                fontFamily: 'Space Grotesk',
                fontSize: 17,
                fontWeight: 900,
                letterSpacing: '-0.05em',
                color: '#e5e1e4',
              }}
            >
              ShopPanel
            </div>
          </div>

          {!isMobile && (
            <React.Fragment>
              {/* Desktop: Nav-Links zentriert */}
              <div style={{ flex: 1, display: 'flex', gap: 4, justifyContent: 'center' }}>
                {NAV_ITEMS.map((item) => (
                  <a
                    key={item.label}
                    href={`#${item.target}`}
                    onClick={(e) => {
                      e.preventDefault()
                      scrollTo(item.target)
                    }}
                    style={{
                      padding: '8px 14px',
                      borderRadius: 9,
                      color: '#a98a7d',
                      textDecoration: 'none',
                      fontSize: 14,
                      fontWeight: 500,
                      transition: 'color .2s,background .2s',
                    }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.color = '#FF6B00'
                      e.currentTarget.style.background = '#201f1f'
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.color = '#a98a7d'
                      e.currentTarget.style.background = 'transparent'
                    }}
                  >
                    {item.label}
                  </a>
                ))}
              </div>
              {/* Desktop: Login text-link + CTA rechts (login first so eyes
                  scan past it on the way to the orange CTA). */}
              <a
                href="/login"
                onClick={(e) => {
                  e.preventDefault()
                  onLoginClick()
                }}
                style={{
                  padding: '8px 14px',
                  color: '#a98a7d',
                  textDecoration: 'none',
                  fontSize: 13,
                  fontWeight: 500,
                  letterSpacing: '-0.005em',
                  transition: 'color .2s',
                }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.color = '#e5e1e4'
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.color = '#a98a7d'
                }}
              >
                Giriş Yap
              </a>
              <button
                onClick={onStartClick}
                className="sp-cta-glow"
                style={{
                  padding: '9px 18px',
                  borderRadius: 9999,
                  background: '#FF6B00',
                  color: '#572000',
                  border: 'none',
                  fontWeight: 700,
                  fontSize: 13,
                  cursor: 'pointer',
                }}
              >
                Başlayın
              </button>
            </React.Fragment>
          )}

          {isMobile && (
            /* Mobile: Login text-link + primary CTA (no hamburger). Logic: users
               scroll through the landing anyway — anchor nav is overkill. Same
               pattern as Stripe, Linear, Notion, Cobalt, ikas. Login-Link added
               2026-05-04 als visible Backup wenn refreshSession() im / handler
               gescheitert ist. */
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
              <a
                href="/login"
                onClick={(e) => {
                  e.preventDefault()
                  onLoginClick()
                }}
                style={{
                  padding: '8px 6px',
                  color: '#a98a7d',
                  textDecoration: 'none',
                  fontSize: 13,
                  fontWeight: 500,
                  letterSpacing: '-0.005em',
                }}
              >
                Giriş Yap
              </a>
              <button
                onClick={onStartClick}
                className="sp-cta-glow"
                style={{
                  padding: '9px 16px',
                  borderRadius: 9999,
                  background: '#FF6B00',
                  color: '#572000',
                  border: 'none',
                  fontWeight: 800,
                  fontSize: 13,
                  cursor: 'pointer',
                  fontFamily: 'Inter',
                  letterSpacing: '-0.01em',
                  flexShrink: 0,
                }}
              >
                Başlayın
              </button>
            </div>
          )}
        </div>
      </nav>
    </React.Fragment>
  )
}

const HeroBody = () => (
  <div
    style={{
      position: 'relative',
      maxWidth: 1280,
      margin: '0 auto',
      textAlign: 'center',
      zIndex: 2,
      padding: '60px 32px 0',
    }}
  >
    <div
      style={{
        display: 'inline-flex',
        alignItems: 'center',
        gap: 8,
        padding: '7px 14px',
        borderRadius: 9999,
        background: 'rgba(19,19,21,0.6)',
        border: '1px solid rgba(93,230,255,0.2)',
        backdropFilter: 'blur(12px)',
        marginBottom: 32,
      }}
    >
      <span
        style={{
          width: 6,
          height: 6,
          borderRadius: 9999,
          background: '#5de6ff',
          boxShadow: '0 0 8px #5de6ff',
          animation: 'sp-pulse 1.6s ease-in-out infinite',
        }}
      />
      <span
        style={{
          fontFamily: 'ui-monospace,monospace',
          fontSize: 10,
          color: '#9ccaff',
          letterSpacing: '0.2em',
          textTransform: 'uppercase',
          fontWeight: 700,
        }}
      >
        E-Ticaret Yeniden Tasarlandı
      </span>
    </div>
    <h1
      style={{
        fontFamily: 'Manrope',
        fontSize: 'clamp(44px, 6vw, 76px)',
        fontWeight: 800,
        letterSpacing: '-0.04em',
        lineHeight: 1.02,
        color: '#e5e1e4',
        margin: '0 0 28px',
        textWrap: 'balance',
      }}
    >
      Birleşik e-ticaretin
      <br />
      gücünü{' '}
      <span
        style={{
          background: 'linear-gradient(90deg,#FF8C33,#FF6B00)',
          WebkitBackgroundClip: 'text',
          backgroundClip: 'text',
          WebkitTextFillColor: 'transparent',
        }}
      >
        serbest bırakın
      </span>
    </h1>
    <p
      style={{
        maxWidth: 680,
        margin: '0 auto 42px',
        fontSize: 18,
        lineHeight: 1.6,
        color: '#a98a7d',
        textWrap: 'pretty',
      }}
    >
      Trendyol, Shopify, Hepsiburada ve n11 hesaplarınızı tek bir kokpite bağlayın. Siparişleri
      onaylayın, stokları yönetin, fiyatları otomatikleştirin — hepsini Genius AI eşliğinde.
    </p>
    <div
      style={{
        display: 'flex',
        gap: 14,
        justifyContent: 'center',
        flexWrap: 'wrap',
        marginBottom: 64,
      }}
    >
      <button
        className="sp-primary-cta sp-cta-glow"
        style={{
          padding: '16px 32px',
          borderRadius: 14,
          background: '#FF6B00',
          color: '#572000',
          border: 'none',
          fontSize: 16,
          fontWeight: 700,
          cursor: 'pointer',
          fontFamily: 'Inter',
          letterSpacing: '-0.01em',
          transform: 'scale(0.96)',
          transition: 'transform .25s, box-shadow .25s',
        }}
      >
        Bekleme Listesine Katıl
      </button>
    </div>
    <div
      style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        gap: 0,
        flexWrap: 'wrap',
        maxWidth: 1400,
        margin: '0 auto',
      }}
    >
      <MockupsStage />
    </div>
  </div>
)

// ========== Mockups stage (scroll-scale-fade, independent per mockup) ==========
// Mimics framer-motion useScroll({target, offset:["start 90%","end start"]}).
// Progress is 0 when the element's top is 90% down the viewport, 1 when its
// bottom crosses the viewport top. Each mockup has its own progress so the
// scale curves differ (monitor grows more dramatically than phone).
const useScrollProgress = (ref) => {
  const [progress, setProgress] = React.useState(0)
  React.useEffect(() => {
    if (!ref.current) return
    let raf = 0
    let last = -1
    const tick = () => {
      if (!ref.current) {
        raf = requestAnimationFrame(tick)
        return
      }
      const rect = ref.current.getBoundingClientRect()
      const vh = window.innerHeight || 800
      const startY = 0.9 * vh
      const endY = -rect.height
      const p = (startY - rect.top) / (startY - endY)
      const clamped = Math.max(0, Math.min(1, p))
      if (Math.abs(clamped - last) > 0.002) {
        last = clamped
        setProgress(clamped)
      }
      raf = requestAnimationFrame(tick)
    }
    tick()
    return () => cancelAnimationFrame(raf)
  }, [])
  return progress
}

const interp = (p, inputs, outputs) => {
  if (p <= inputs[0]) return outputs[0]
  if (p >= inputs[inputs.length - 1]) return outputs[outputs.length - 1]
  for (let i = 0; i < inputs.length - 1; i++) {
    if (p >= inputs[i] && p <= inputs[i + 1]) {
      const t = (p - inputs[i]) / (inputs[i + 1] - inputs[i])
      return outputs[i] + t * (outputs[i + 1] - outputs[i])
    }
  }
  return outputs[0]
}

const MockupsStage = () => {
  const monitorRef = React.useRef(null)
  const phoneRef = React.useRef(null)
  const monitorProgress = useScrollProgress(monitorRef)
  const phoneProgress = useScrollProgress(phoneRef)

  // Mobile detection — auf Mobile keine negativen Overlaps + kleinere Scale
  const [isMobile, setIsMobile] = React.useState(
    typeof window !== 'undefined' && window.innerWidth < 768,
  )
  React.useEffect(() => {
    const onResize = () => setIsMobile(window.innerWidth < 768)
    window.addEventListener('resize', onResize)
    return () => window.removeEventListener('resize', onResize)
  }, [])

  const monitorScale = isMobile
    ? interp(monitorProgress, [0, 0.4, 1], [1, 1.05, 1.15])
    : interp(monitorProgress, [0, 0.4, 1], [1.2, 1.38, 1.68])
  // Full opacity while mockup sits in lower viewport, gentle fade as it scrolls up
  // End opacity ~0.25 so it's visible but "receding" when leaving the screen
  const monitorOpacity = interp(monitorProgress, [0, 0.4, 0.9], [1, 1, 0.25])
  const phoneScale = isMobile
    ? interp(phoneProgress, [0, 0.4, 1], [0.9, 0.95, 1.0])
    : interp(phoneProgress, [0, 0.4, 1], [1, 1.1, 1.3])
  const phoneOpacity = interp(phoneProgress, [0, 0.4, 0.9], [1, 1, 0.25])

  return (
    <React.Fragment>
      <div
        ref={monitorRef}
        style={{
          animation: 'sp-float 7s ease-in-out infinite',
          flex: isMobile ? '1 1 100%' : '0 1 820px',
          minWidth: 0,
          display: 'flex',
          justifyContent: 'center',
          willChange: 'transform,opacity',
          transformOrigin: 'center center',
          marginRight: isMobile ? 0 : -30,
          marginBottom: isMobile ? 24 : 0,
          transform: `scale(${monitorScale})`,
          opacity: monitorOpacity,
        }}
      >
        <HeroMonitor />
      </div>
      <div
        ref={phoneRef}
        style={{
          animation: 'sp-float 8s ease-in-out infinite',
          animationDelay: '-1s',
          willChange: 'transform,opacity',
          transformOrigin: 'center center',
          marginLeft: isMobile ? 0 : -30,
          transform: `scale(${phoneScale})`,
          opacity: phoneOpacity,
          display: isMobile ? 'flex' : 'block',
          justifyContent: isMobile ? 'center' : undefined,
          width: isMobile ? '100%' : undefined,
        }}
      >
        <HeroPhone />
      </div>
    </React.Fragment>
  )
}
window.MockupsStage = MockupsStage

// Feature grid header + cards (extracted so variants can wrap it)
const FeatureGridInner = () => (
  <div style={{ maxWidth: 1280, margin: '0 auto', padding: '0 32px' }}>
    <div style={{ textAlign: 'center', marginBottom: 56 }}>
      <div
        style={{
          fontFamily: 'ui-monospace,monospace',
          fontSize: 10,
          color: '#FF6B00',
          letterSpacing: '0.25em',
          textTransform: 'uppercase',
          fontWeight: 700,
          marginBottom: 14,
        }}
      >
        Özellikler
      </div>
      <h2
        style={{
          fontFamily: 'Manrope',
          fontSize: 'clamp(36px, 4vw, 56px)',
          fontWeight: 800,
          letterSpacing: '-0.03em',
          color: '#e5e1e4',
          margin: '0 0 16px',
          textWrap: 'balance',
          lineHeight: 1.05,
        }}
      >
        İhtiyacınız olan her şey.
        <br />
        Olmayan hiçbir şey.
      </h2>
      <p
        style={{
          maxWidth: 620,
          margin: '0 auto',
          fontSize: 17,
          color: '#a98a7d',
          lineHeight: 1.6,
          textWrap: 'pretty',
        }}
      >
        Dijital perakende mimarları için inşa edildi. Mimari seviyede performans, sıfır taviz.
      </p>
    </div>
    <div
      style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(auto-fit, minmax(340px, 1fr))',
        gap: 24,
        maxWidth: 1180,
        margin: '0 auto',
      }}
    >
      <FeatureCard
        icon="hub"
        title="4 pazaryeri, tek panel"
        accent="#FF6B00"
        copy="Trendyol, Shopify, Hepsiburada ve n11 hesaplarınızı bir kez bağlayın. Siparişler, stoklar, fiyatlar — hepsi tek noktadan."
        visual={<VisualPlatformGrid />}
      />
      <FeatureCard
        icon="auto_awesome"
        title="Genius AI operasyon ortağınız"
        accent="#5de6ff"
        copy="Fiyat kuralları önerir, stok uyarıları yapar, müşteri mesajlarına taslak hazırlar. Siz onaylayın, o uygulasın."
        visual={<VisualGeniusBubble />}
      />
      <FeatureCard
        icon="bolt"
        title="Gerçek zamanlı dashboard"
        accent="#34d399"
        copy="Son 24 saatte ne oldu? Canlı KPI'lar, tabular mono sayılar, her pazaryeri için ayrı sağlık durumu."
        visual={<VisualKpiTrio />}
      />
    </div>
  </div>
)

Object.assign(window, { Particles, BackgroundStack, LandingNav, HeroBody, FeatureGridInner })
