import { useState, useEffect, useRef } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { ChevronRight } from 'lucide-react'
import { Sidebar } from '../components/Sidebar'
import type { User } from '../types'

export function AppFrame({ user }: { user: User }) {
  const { slug } = useParams<{ slug: string }>()
  const navigate = useNavigate()
  const app = user.apps.find(a => a.slug === slug)
  const [menuOpen, setMenuOpen] = useState(false)
  const iframeRef = useRef<HTMLIFrameElement>(null)

  // Capture hash once at mount — before iframe navigation overwrites it
  const [initialSrc] = useState(() => {
    if (!app) return ''
    const sub = window.location.hash.slice(1)
    return sub && sub !== '/' ? `${app.base_path}${sub}` : `${app.base_path}/`
  })

  // Clear hash when switching apps
  useEffect(() => {
    return () => { history.replaceState(null, '', window.location.pathname) }
  }, [slug])

  // Auto-close when user clicks into / navigates within the iframe
  useEffect(() => {
    if (!menuOpen) return
    const close = () => setMenuOpen(false)
    window.addEventListener('blur', close)
    return () => window.removeEventListener('blur', close)
  }, [menuOpen])

  function handleIframeLoad() {
    try {
      const iframePath = iframeRef.current?.contentWindow?.location.pathname ?? ''
      const relative = iframePath.replace(app!.base_path, '') || '/'
      if (relative !== '/') {
        history.replaceState(null, '', `/app/${slug}#${relative}`)
      }
    } catch {
      // cross-origin guard — won't trigger in this same-origin stack
    }
  }

  if (!app) {
    return (
      <div style={{ height: '100dvh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div style={{ textAlign: 'center' }}>
          <p style={{ color: 'var(--text-muted)', marginBottom: '1rem' }}>App not found or not permitted.</p>
          <button onClick={() => navigate('/')} style={{
            background: 'var(--gold)', color: 'var(--navy-dark)', border: 'none',
            borderRadius: '6px', padding: '0.5rem 1.25rem', fontWeight: 600,
          }}>
            Back to dashboard
          </button>
        </div>
      </div>
    )
  }

  return (
    <div style={{ display: 'flex', height: '100dvh' }}>

      {/* Collapsed sidebar strip */}
      <div style={{
        width: 44, flexShrink: 0,
        background: 'var(--navy)', borderRight: '1px solid var(--surface-2)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        height: '100dvh', position: 'sticky', top: 0,
      }}>
        <button
          onClick={() => setMenuOpen(true)}
          title="Open menu"
          style={{
            background: 'none', border: 'none', cursor: 'pointer',
            color: 'var(--text-muted)', padding: '0.5rem',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            borderRadius: 6,
          }}
        >
          <ChevronRight size={18} strokeWidth={1.75} />
        </button>
      </div>

      {/* Overlay sidebar + backdrop when open */}
      {menuOpen && (
        <>
          <div
            onClick={() => setMenuOpen(false)}
            style={{ position: 'fixed', inset: 0, zIndex: 19, background: 'rgba(0,0,0,0.35)' }}
          />
          <div style={{ position: 'fixed', left: 0, top: 0, height: '100dvh', zIndex: 20 }}>
            <Sidebar user={user} activeSlug={slug} onCollapse={() => setMenuOpen(false)} />
          </div>
        </>
      )}

      {/* App iframe */}
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
        <div style={{ height: '3px', background: app.theme_color, flexShrink: 0 }} />
        <iframe
          ref={iframeRef}
          src={initialSrc}
          title={app.name}
          style={{ flex: 1, border: 'none', width: '100%' }}
          allow="clipboard-read; clipboard-write"
          onLoad={handleIframeLoad}
        />
      </div>
    </div>
  )
}
