'use client'
import { useEffect, useState } from 'react'
import { isSuppressed, type PoliticasData } from '@/lib/dashboard-types'
import { queries } from '@/lib/dashboard-queries'
import type { DashboardFilters } from '@/lib/dashboard-types'
import { WidgetShell } from './widget-shell'

export function PoliticasBar({ surveyId, filters }: { surveyId: string; filters: DashboardFilters }) {
  const [data, setData] = useState<PoliticasData | null>(null)
  const [sup, setSup] = useState(false)

  useEffect(() => {
    setData(null); setSup(false)
    queries.politicas(surveyId, filters)
      .then(d => { if (isSuppressed(d)) setSup(true); else setData(d as PoliticasData) })
      .catch(() => {})
  }, [surveyId, JSON.stringify(filters)])

  const status = !data && !sup ? 'loading' : sup ? 'suppressed' : 'ok'

  return (
    <WidgetShell title="📈 Políticas más demandadas" status={status} n={data?.n_total} colSpan={6}>
      {data && (
        <ul className="db-bar-list" aria-label="Políticas demandadas">
          {data.data.length === 0 && (
            <li className="db-suppressed-hint">No hay datos suficientes por política (n&lt;5 en todas).</li>
          )}
          {data.data.map(item => (
            <li key={item.politica} className="db-bar-item">
              <span className="db-bar-label">{item.politica}</span>
              <div className="db-bar-track" aria-hidden="true">
                <div className="db-bar-fill"
                  style={{ width: `${item.pct}%`, background: '#43BBC8' }} />
              </div>
              <span className="db-bar-pct">{item.pct}%</span>
            </li>
          ))}
        </ul>
      )}
    </WidgetShell>
  )
}
