import { useEffect, useState } from 'react'
import { Outlet } from 'react-router-dom'
import { isAbortError } from '../../lib/api'
import { getTenantDomain } from '../../lib/config'
import { CheckoutProvider } from '../../context/CheckoutContext'
import { getWebsiteBusinessInfo, getWebsiteUrl } from '../../services/websiteService'
import meshkeeLogo from '../../assets/meshkee-logo.png'
import styles from './CheckoutLayout.module.css'

export function CheckoutLayout() {
  const tenantDomain = getTenantDomain()
  const websiteUrl = getWebsiteUrl(tenantDomain)
  const [brandName, setBrandName] = useState('')
  const [logoUrl, setLogoUrl] = useState<string | null>(null)

  useEffect(() => {
    const controller = new AbortController()

    async function loadBranding() {
      try {
        const info = await getWebsiteBusinessInfo(tenantDomain, controller.signal)
        if (controller.signal.aborted) return
        setBrandName(info.nameFa?.trim() || info.name.trim() || tenantDomain)
        setLogoUrl(info.logoUrl?.trim() || null)
      } catch (err) {
        if (isAbortError(err)) return
        setBrandName(tenantDomain)
        setLogoUrl(null)
      }
    }

    void loadBranding()
    return () => controller.abort()
  }, [tenantDomain])

  const displayName = brandName || tenantDomain

  return (
    <CheckoutProvider>
      <div className={styles.checkoutPage} lang="fa" dir="rtl">
        <header className={styles.header}>
          <a href={websiteUrl} className={styles.brandLink}>
            <img
              src={logoUrl || meshkeeLogo}
              alt={displayName}
              className={styles.logo}
            />
            <div className={styles.brandText}>
              <span className={styles.brandTitle}>{displayName}</span>
              <span className={styles.subtitle}>سبد خرید</span>
            </div>
          </a>
        </header>

        <main className={styles.main}>
          <div className={styles.container}>
            <div className={styles.card}>
              <Outlet />
            </div>
          </div>
        </main>
      </div>
    </CheckoutProvider>
  )
}
