import { type ReactNode, useEffect, useState } from 'react'
import { NamedAgentSpinner } from './agent-spinners'

export function GeneralPageLoader({
  title = 'Loading',
  description,
  children,
  eyebrow,
  fullscreen = false,
  showBrand = false,
}: {
  title?: string
  description?: string
  children?: ReactNode
  eyebrow?: string
  fullscreen?: boolean
  showBrand?: boolean
}) {
  const [isCompleting, setIsCompleting] = useState(false)

  useEffect(() => {
    const pulseTimer = window.setTimeout(() => {
      setIsCompleting(true)
    }, 900)
    const clearTimer = window.setTimeout(() => {
      setIsCompleting(false)
    }, 1550)

    return () => {
      window.clearTimeout(pulseTimer)
      window.clearTimeout(clearTimer)
    }
  }, [])

  const spinnerColor = isCompleting ? 'var(--ht-amber)' : 'var(--ht-cyan)'

  return (
    <div
      className={`general-page-loader-shell${fullscreen ? ' general-page-loader-shell--fullscreen' : ''}`}
      role="status"
      aria-live="polite"
      aria-label={title}
    >
      <div className="general-page-loader-frame">
        {showBrand ? (
          <div className="general-page-loader-brand">
            <img
              src="/branding/hypertwist-3d-symbol.png"
              alt="HyperTwist"
              className="general-page-loader-brand__image"
            />
          </div>
        ) : null}
        {eyebrow ? <p className="general-page-loader-eyebrow">{eyebrow}</p> : null}
        <NamedAgentSpinner
          name="cascade"
          size={32}
          color={spinnerColor}
          className={`loading-spinner ${isCompleting ? 'is-completing' : ''}`}
        />
        <p className="general-page-loader-text">{title}</p>
        {description ? <p className="general-page-loader-body">{description}</p> : null}
        {children ? <div className="general-page-loader-extra">{children}</div> : null}
      </div>
    </div>
  )
}
