/**
 * BoostMedia AI Content Generator Admin - Layout Component
 *
 * @package BoostMedia_AI
 * @license GPL-2.0-or-later
 */

import { useState, useEffect } from 'react'
import { Outlet, useLocation, useNavigate } from 'react-router-dom'
import { AlertTriangle, X, Coins } from 'lucide-react'
import { Sidebar } from './Sidebar'
import { useDataLanguage } from '../../lib/DataLanguageContext'
import { useTranslation } from '../../lib/TranslationContext'
import { endpoints } from '../../api/client'
import { t, tf } from '../../lib/i18n'

function LowCreditsAlert() {
  const navigate = useNavigate()
  const [visible, setVisible] = useState(false)
  const [remaining, setRemaining] = useState(0)
  const [dismissed, setDismissed] = useState(false)

  useEffect(() => {
    const check = async () => {
      try {
        const [creditsRes, settingsRes] = await Promise.all([
          endpoints.getCreditsStatus(),
          endpoints.getSettings(),
        ])
        const credits = creditsRes.data as any
        const settings = settingsRes.data as any
        const rawThreshold = Number(settings?.low_credits_threshold)
        const threshold = Number.isNaN(rawThreshold) ? 100 : rawThreshold
        const rem = credits?.boost_credits?.remaining ?? 0
        setRemaining(Math.round(rem))
        if (threshold > 0 && rem < threshold && rem >= 0) {
          setVisible(true)
        }
      } catch { /* ignore */ }
    }
    check()
  }, [])

  if (!visible || dismissed) return null

  return (
    <div className="bg-amber-50 border-b border-amber-200 px-6 py-2.5 flex items-center gap-3">
      <AlertTriangle className="w-4 h-4 text-amber-600 flex-shrink-0" />
      <p className="text-sm text-amber-800 flex-1">
        <Coins className="w-3.5 h-3.5 inline-block me-1 -mt-0.5" />
        {tf('Low BoostCoins balance: %s remaining.', remaining)}{' '}
        <button
          type="button"
          onClick={() => navigate('/usage')}
          className="text-amber-700 font-semibold underline hover:text-amber-900 bg-transparent border-none cursor-pointer p-0"
        >
          {t('Purchase more')}
        </button>
      </p>
      <button
        type="button"
        onClick={() => setDismissed(true)}
        className="p-0.5 text-amber-400 hover:text-amber-600 bg-transparent border-none cursor-pointer"
      >
        <X className="w-3.5 h-3.5" />
      </button>
    </div>
  )
}

export default function Layout() {
  const { isRtl } = useTranslation()
  const { dataLanguage } = useDataLanguage()
  const location = useLocation()

  useEffect(() => {
    window.scrollTo(0, 0)
  }, [location.pathname])

  return (
    <div className={`min-h-screen w-full bg-bc-gray-50 flex ${isRtl ? 'flex-row-reverse' : 'flex-row'}`}>
      <Sidebar />
      <main className="flex-1 min-w-0">
        <div className="min-h-screen">
          <LowCreditsAlert />
          <div key={dataLanguage}>
            <Outlet />
          </div>
        </div>
      </main>
    </div>
  )
}
