'use client'

import { useEffect, useState } from 'react'
import { usePathname } from 'next/navigation'
import { useMarketplacePreferences } from './MarketplaceShell'

type FrameId = 'dashboard' | 'admin' | 'public-site'

const frameConfig: Record<FrameId, { label: string; port: number; path: string }> = {
  dashboard: {
    label: 'Company Workspace',
    port: 3001,
    path: '/sign-in',
  },
  admin: {
    label: 'Platform Operations',
    port: 3002,
    path: '/',
  },
  'public-site': {
    label: 'Branded Website',
    port: 3003,
    path: '/',
  },
}

function withPort(port: number, path: string) {
  if (typeof window === 'undefined') return path

  const url = new URL(window.location.href)
  url.port = String(port)
  url.pathname = path
  url.search = ''
  url.hash = ''
  return url.toString()
}

export default function WorkspaceFrame({ target }: { target: FrameId }) {
  const pathname = usePathname()
  const { language } = useMarketplacePreferences()
  const [src, setSrc] = useState('')
  const config = frameConfig[target]
  const fillViewport = pathname === '/company-workspace'
  const frameHeight = fillViewport ? '100vh' : 'calc(100vh - 56px)'
  const loadingLabel = {
    en: 'Loading',
    fr: 'Chargement de',
    ar: 'جارٍ تحميل',
  }[language]

  useEffect(() => {
    setSrc(withPort(config.port, config.path))
  }, [config.path, config.port])

  return (
    <main className="bg-stone-950" style={{ minHeight: frameHeight }}>
      {src ? (
        <iframe
          title={config.label}
          src={src}
          className="w-full border-0 bg-white"
          style={{ height: frameHeight }}
        />
      ) : (
        <div className="flex items-center justify-center text-sm text-stone-300" style={{ height: frameHeight }}>
          {loadingLabel} {config.label}…
        </div>
      )}
    </main>
  )
}
