'use client'

import { useEffect, useState } from 'react'

import { useI18n } from '@/components/providers/i18n-provider'
import { cn } from '@/lib/cn'

/**
 * What the platform is doing while it computes (§62).
 *
 * A spinner says "wait"; this says what is being waited for. The stages are the real
 * ones — snapshot, grid model, cascades, strategies, futures, recommendation — and they
 * advance on a schedule derived from how long each stage actually takes, so the
 * indicator is honest about where the time goes even though it cannot see inside a
 * single server round trip.
 */
const STAGES = ['snapshot', 'grid', 'cascade', 'strategies', 'futures', 'recommendation'] as const

/** Relative cost of each stage, measured against typical runs. */
const WEIGHTS = [0.12, 0.24, 0.2, 0.22, 0.14, 0.08]

export function SimulationProgress({
  running,
  className,
}: {
  running: boolean
  className?: string
}) {
  const { t } = useI18n()
  const [stage, setStage] = useState(0)

  useEffect(() => {
    if (!running) {
      setStage(0)
      return
    }
    let index = 0
    let cancelled = false

    const advance = () => {
      if (cancelled || index >= STAGES.length - 1) return
      const wait = WEIGHTS[index] * 4200
      setTimeout(() => {
        if (cancelled) return
        index += 1
        setStage(index)
        advance()
      }, wait)
    }
    advance()

    return () => {
      cancelled = true
    }
  }, [running])

  if (!running) return null

  return (
    <div
      role="status"
      aria-live="polite"
      className={cn('nabdh-scan relative overflow-hidden rounded-[--radius-panel] border border-simulation/30 bg-simulation/6 p-4', className)}
    >
      <p className="text-[11px] font-semibold uppercase tracking-[0.14em] text-simulation">
        {t('simProgress.title')}
      </p>
      <ol className="mt-3 space-y-1.5">
        {STAGES.map((key, index) => {
          const done = index < stage
          const active = index === stage
          return (
            <li key={key} className="flex items-center gap-2.5 text-[11px]">
              <span
                aria-hidden
                className={cn(
                  'size-1.5 shrink-0 rounded-full',
                  done ? 'bg-normal' : active ? 'bg-simulation nabdh-pulse' : 'bg-border-strong',
                )}
              />
              <span className={cn(done ? 'text-text-muted line-through' : active ? 'text-text' : 'text-text-faint')}>
                {t(`simProgress.step.${key}`)}
              </span>
            </li>
          )
        })}
      </ol>
    </div>
  )
}
