'use client'

import { useI18n } from '@/components/providers/i18n-provider'
import { cn } from '@/lib/cn'
import { riskToState } from '@/lib/domain/enums'
import { styleForRisk } from '@/lib/ui/state-styles'

/**
 * The risk dial.
 *
 * A 240° arc rather than a full circle so the empty sweep reads as "headroom" instead of
 * looking like an incomplete ring. Band boundaries are drawn on the track, which lets an
 * operator see how close a value sits to the next threshold without reading the number.
 */
export function RiskGauge({
  value,
  size = 168,
  label,
  sublabel,
  className,
  showBands = true,
}: {
  value: number
  size?: number
  label?: string
  sublabel?: string
  className?: string
  showBands?: boolean
}) {
  const { t, n } = useI18n()
  const style = styleForRisk(value)
  const state = riskToState(value)

  const stroke = size * 0.085
  const radius = (size - stroke) / 2
  const centre = size / 2
  const startAngle = 150
  const sweep = 240

  const polar = (angleDeg: number, r = radius) => {
    const rad = (angleDeg * Math.PI) / 180
    return { x: centre + r * Math.cos(rad), y: centre + r * Math.sin(rad) }
  }

  const arcPath = (fromPct: number, toPct: number, r = radius) => {
    const from = polar(startAngle + sweep * fromPct, r)
    const to = polar(startAngle + sweep * toPct, r)
    const large = sweep * (toPct - fromPct) > 180 ? 1 : 0
    return `M ${from.x} ${from.y} A ${r} ${r} 0 ${large} 1 ${to.x} ${to.y}`
  }

  const clamped = Math.max(0, Math.min(100, value))
  const bands = [
    { to: 0.35, color: '#10b981' },
    { to: 0.55, color: '#fbbf24' },
    { to: 0.75, color: '#f97316' },
    { to: 0.9, color: '#ef4444' },
    { to: 1, color: '#ff3d71' },
  ]

  return (
    <div className={cn('flex flex-col items-center', className)}>
      <div className="relative" style={{ width: size, height: size * 0.78 }}>
        <svg
          width={size}
          height={size}
          viewBox={`0 0 ${size} ${size}`}
          className="absolute inset-x-0 top-0"
          role="img"
          aria-label={t('a11y.riskGauge', { value: Math.round(clamped) })}
        >
          {/* Track */}
          <path
            d={arcPath(0, 1)}
            fill="none"
            stroke="#16233a"
            strokeWidth={stroke}
            strokeLinecap="round"
          />

          {/* Band markers on the track */}
          {showBands
            ? bands.slice(0, -1).map((band) => {
                const point = polar(startAngle + sweep * band.to, radius)
                const inner = polar(startAngle + sweep * band.to, radius - stroke / 2)
                return (
                  <line
                    key={band.to}
                    x1={inner.x}
                    y1={inner.y}
                    x2={point.x}
                    y2={point.y}
                    stroke="#05080f"
                    strokeWidth="2"
                  />
                )
              })
            : null}

          {/* Value arc */}
          <path
            d={arcPath(0, Math.max(0.001, clamped / 100))}
            fill="none"
            stroke={style.hex}
            strokeWidth={stroke}
            strokeLinecap="round"
            style={{ transition: 'd 600ms ease-out' }}
          />

          {/* Needle tip */}
          {(() => {
            const tip = polar(startAngle + sweep * (clamped / 100), radius)
            return <circle cx={tip.x} cy={tip.y} r={stroke * 0.55} fill="#05080f" stroke={style.hex} strokeWidth="2.5" />
          })()}
        </svg>

        <div className="absolute inset-x-0 top-[38%] flex flex-col items-center">
          <span className={cn('tnum text-3xl font-semibold tracking-tight', style.text)}>
            {n(clamped, { maximumFractionDigits: 0 })}
            <span className="text-base font-medium">%</span>
          </span>
          <span className={cn('mt-0.5 text-[11px] font-medium', style.text)}>
            {t(`states.${state}`)}
          </span>
        </div>
      </div>

      {label ? <p className="mt-1 text-xs font-medium text-text">{label}</p> : null}
      {sublabel ? <p className="mt-0.5 text-[11px] text-text-muted">{sublabel}</p> : null}
    </div>
  )
}

/**
 * The before/after pair that the SIMULATE action produces. Deliberately large: this is
 * the moment the platform's value is either obvious or it isn't.
 */
export function RiskDelta({
  before,
  after,
  beforeLabel,
  afterLabel,
  note,
  className,
}: {
  before: number
  after: number
  beforeLabel: string
  afterLabel: string
  note?: string
  className?: string
}) {
  const { n } = useI18n()
  const beforeStyle = styleForRisk(before)
  const afterStyle = styleForRisk(after)

  return (
    <div className={cn('rounded-[--radius-panel] border border-border bg-surface-2/50 p-5', className)}>
      <div className="flex items-center justify-center gap-5 sm:gap-8">
        <div className="text-center">
          <p className="text-[11px] uppercase tracking-wide text-text-faint">{beforeLabel}</p>
          <p className={cn('tnum mt-1 text-4xl font-semibold sm:text-5xl', beforeStyle.text)}>
            {n(before, { maximumFractionDigits: 0 })}
            <span className="text-xl">%</span>
          </p>
        </div>

        <svg viewBox="0 0 40 24" className="h-6 w-10 shrink-0 text-brand rtl:-scale-x-100" aria-hidden>
          <path
            d="M2 12h32m0 0-7-7m7 7-7 7"
            fill="none"
            stroke="currentColor"
            strokeWidth="2.2"
            strokeLinecap="round"
            strokeLinejoin="round"
          />
        </svg>

        <div className="text-center">
          <p className="text-[11px] uppercase tracking-wide text-text-faint">{afterLabel}</p>
          <p className={cn('tnum mt-1 text-4xl font-semibold sm:text-5xl', afterStyle.text)}>
            {n(after, { maximumFractionDigits: 0 })}
            <span className="text-xl">%</span>
          </p>
        </div>
      </div>

      {note ? (
        <p className="mt-4 text-center text-xs leading-relaxed text-text-muted">{note}</p>
      ) : null}
    </div>
  )
}
