// =============================================================
// AdminIncidentList.jsx — ヒヤリハット一覧（管理者）
// =============================================================

const { useState: useStateIL, useMemo: useMemoIL } = React;

// ─── リスクレベルバッジ ──────────────────────────────────────

const RiskBadge = ({ riskLevelId, size = 'sm' }) => {
  const rl = (window.MASTER_RISK_LEVELS || []).find(r => r.id === riskLevelId);
  if (!rl) return null;
  return (
    <span
      className="inline-block font-bold rounded-full text-white whitespace-nowrap"
      style={{
        backgroundColor: rl.color,
        fontSize: size === 'sm' ? 10 : 12,
        padding: size === 'sm' ? '2px 8px' : '3px 10px',
      }}
    >
      {rl.name}
    </span>
  );
};

// ─── ハザード別横棒チャート ──────────────────────────────────

const HazardBarChart = ({ data }) => {
  const max = data[0]?.count || 1;
  const HAZARD_COLORS = ['#6366f1','#3b82f6','#f59e0b','#ef4444','#10b981','#8b5cf6','#f97316','#06b6d4'];
  return (
    <div className="space-y-2.5">
      {data.map(({ hazard, count }, i) => (
        <div key={hazard.id} className="flex items-center gap-2">
          <span className="text-[11px] text-slate-500 w-40 flex-shrink-0 truncate leading-tight">{hazard.name}</span>
          <div className="flex-1 h-3 bg-slate-100 rounded-full overflow-hidden">
            <div
              className="h-full rounded-full transition-all"
              style={{ width: `${(count / max) * 100}%`, backgroundColor: HAZARD_COLORS[i % HAZARD_COLORS.length] }}
            />
          </div>
          <span className="text-[11px] font-bold text-slate-600 w-6 text-right flex-shrink-0">{count}</span>
        </div>
      ))}
    </div>
  );
};

// ─── 月別件数バーチャート ────────────────────────────────────

const IncidentMonthChart = ({ data }) => {
  const maxCount = Math.max(...data.map(d => d.fsi + d.hiyari), 1);
  const BAR_H = 72;
  return (
    <div className="flex items-end gap-1" style={{ height: BAR_H + 36 }}>
      {data.map(({ label, fsi, hiyari }) => {
        const total = fsi + hiyari;
        const fsiFrac   = total > 0 ? fsi   / maxCount : 0;
        const hiyariFrac = total > 0 ? hiyari / maxCount : 0;
        return (
          <div key={label} className="flex-1 flex flex-col items-center gap-0.5">
            <span className="text-[8px] text-slate-400 mb-0.5">{total > 0 ? total : ''}</span>
            <div className="w-full flex flex-col justify-end gap-0" style={{ height: BAR_H }}>
              {/* FSI スタック */}
              {fsi > 0 && (
                <div
                  className="w-full rounded-t-sm"
                  style={{ height: Math.max(2, fsiFrac * BAR_H), backgroundColor: '#6366f1' }}
                />
              )}
              {/* ヒヤリハット スタック */}
              {hiyari > 0 && (
                <div
                  className="w-full"
                  style={{
                    height: Math.max(2, hiyariFrac * BAR_H),
                    backgroundColor: '#f59e0b',
                    borderRadius: fsi === 0 ? '2px 2px 0 0' : '0',
                  }}
                />
              )}
              {total === 0 && <div className="w-full h-0.5 bg-slate-100 rounded-full" />}
            </div>
            <span className="text-[8px] text-slate-400 mt-0.5 text-center w-full truncate">{label}</span>
          </div>
        );
      })}
    </div>
  );
};

// ─── リスクアセスメントチャート ──────────────────────────────

const RiskAssessmentChart = ({ incidents }) => {
  const [chartCenter, setChartCenter] = useStateIL('all');
  const riskLevels = window.MASTER_RISK_LEVELS || [];
  const centers    = window.MASTER_CENTERS    || [];

  const years = useMemoIL(() =>
    [...new Set(incidents.map(i => i.discovery_date.slice(0, 4)))].sort()
  , [incidents]);

  const yearGroups = useMemoIL(() => {
    const makeRow = (label, incs, isBold) => ({
      label, isBold, total: incs.length,
      segments: riskLevels
        .map(rl => ({ rl, count: incs.filter(i => i.risk_level_id === rl.id).length }))
        .filter(s => s.count > 0),
    });
    return years.map(year => {
      const yIncs = incidents.filter(i => i.discovery_date.startsWith(year));
      const rows  = [];
      if (chartCenter === 'all') {
        rows.push(makeRow('全体', yIncs, true));
        centers.forEach(c =>
          rows.push(makeRow(c.name, yIncs.filter(i => i.center_id === c.id), false))
        );
      } else {
        const cId = parseInt(chartCenter);
        const c   = centers.find(cx => cx.id === cId);
        rows.push(makeRow(c?.name || '—', yIncs.filter(i => i.center_id === cId), true));
      }
      return { year, rows };
    });
  }, [incidents, chartCenter, years]);

  const maxTotal = useMemoIL(() =>
    Math.max(...yearGroups.flatMap(g => g.rows.map(r => r.total)), 1)
  , [yearGroups]);

  const ticks = useMemoIL(() => {
    const step = Math.ceil(maxTotal / 5);
    const result = [0];
    for (let v = step; v <= maxTotal; v += step) result.push(v);
    if (result[result.length - 1] < maxTotal) result.push(maxTotal);
    return result;
  }, [maxTotal]);

  const selectedLabel = chartCenter === 'all'
    ? '全体'
    : (centers.find(c => c.id === parseInt(chartCenter))?.name || '');

  const YEAR_W  = 28;
  const LABEL_W = 80;
  const COUNT_W = 28;

  return (
    <div className="bg-white rounded-2xl border border-slate-200 p-5">
      {/* ヘッダ + センター切り替え */}
      <div className="flex items-center justify-between flex-wrap gap-3 mb-5">
        <h2 className="text-sm font-bold text-slate-700">
          リスクアセスメント（{selectedLabel}）
        </h2>
        <div className="flex items-center gap-1 flex-wrap">
          {[{ id: 'all', name: '全体' }, ...centers].map(c => (
            <button
              key={c.id}
              onClick={() => setChartCenter(String(c.id))}
              className="text-xs px-3 py-1 rounded-full transition-all font-medium"
              style={{
                backgroundColor: String(c.id) === chartCenter ? '#6366f1' : '#f1f5f9',
                color:            String(c.id) === chartCenter ? '#fff'    : '#64748b',
              }}
            >
              {c.name}
            </button>
          ))}
        </div>
      </div>

      {/* チャート本体 */}
      <div className="overflow-x-auto">
        <div className="space-y-5" style={{ minWidth: 320 }}>
          {yearGroups.map(({ year, rows }) => (
            <div key={year} className="flex gap-1 items-stretch">
              {/* 年ラベル（縦書き） */}
              <div
                className="flex items-center justify-center flex-shrink-0 text-slate-400 font-bold"
                style={{ width: YEAR_W, fontSize: 11, writingMode: 'vertical-rl', transform: 'rotate(180deg)' }}
              >
                {year}
              </div>

              {/* バー行群 */}
              <div className="flex-1 space-y-1.5">
                {rows.map((row, ri) => (
                  <div key={ri} className="flex items-center gap-2">
                    {/* センター名 */}
                    <span
                      className="text-right flex-shrink-0 truncate text-slate-500"
                      style={{ width: LABEL_W, fontSize: row.isBold ? 11 : 10, fontWeight: row.isBold ? 700 : 400 }}
                    >
                      {row.label}
                    </span>

                    {/* 積み上げバー */}
                    <div
                      className="flex-1 h-6 rounded-sm flex overflow-hidden"
                      style={{
                        backgroundColor: '#f8fafc',
                        background: `repeating-linear-gradient(90deg,transparent 0%,transparent calc(${100 / ticks.length}% - 0.5px),#e2e8f0 calc(${100 / ticks.length}% - 0.5px),#e2e8f0 ${100 / ticks.length}%), #f8fafc`,
                      }}
                    >
                      {row.segments.map(({ rl, count }) => (
                        <div
                          key={rl.id}
                          title={`${rl.name}: ${count}件`}
                          className="h-full"
                          style={{
                            width: `${(count / maxTotal) * 100}%`,
                            backgroundColor: rl.color,
                            minWidth: 2,
                          }}
                        />
                      ))}
                    </div>

                    {/* 件数 */}
                    <span
                      className="text-slate-400 text-right flex-shrink-0"
                      style={{ width: COUNT_W, fontSize: 10 }}
                    >
                      {row.total > 0 ? row.total : ''}
                    </span>
                  </div>
                ))}
              </div>
            </div>
          ))}

          {/* X軸ラベル */}
          <div className="flex items-center" style={{ paddingLeft: YEAR_W + 4 + LABEL_W + 8 }}>
            <div className="flex-1 relative h-4">
              {ticks.map(v => (
                <span
                  key={v}
                  className="absolute text-[10px] text-slate-400"
                  style={{ left: `${(v / maxTotal) * 100}%`, transform: 'translateX(-50%)' }}
                >
                  {v}
                </span>
              ))}
            </div>
            <div style={{ width: COUNT_W + 8 }} />
          </div>
        </div>
      </div>

      {/* 凡例 */}
      <div className="flex flex-wrap gap-x-4 gap-y-2 mt-4 justify-center">
        {riskLevels.map(rl => (
          <div key={rl.id} className="flex items-center gap-1.5">
            <span className="w-3 h-3 rounded-sm flex-shrink-0" style={{ backgroundColor: rl.color }} />
            <span className="text-[11px] text-slate-500">{rl.name}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

// ─── 詳細モーダル ────────────────────────────────────────────

const IncidentDetailModal = ({ incident, onClose }) => {
  if (!incident) return null;
  const { X, Building2, AlertTriangle, AlertCircle } = window.LucideReact;
  const center  = window.MASTER_CENTERS.find(c => c.id === incident.center_id);
  const user    = window.MASTER_USERS.find(u => u.id === incident.reported_by);
  const hazard  = window.MASTER_HAZARDS.find(h => h.id === incident.hazard_id);
  const injury  = window.MASTER_INJURY_TYPES.find(i => i.id === incident.injury_type_id);
  const isFsi   = incident.discovery_type === 'FSI';

  return (
    <div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center">
      <div className="absolute inset-0 bg-black/40 backdrop-blur-[2px]" onClick={onClose} />
      <div className="relative bg-white w-full max-w-lg rounded-t-3xl sm:rounded-2xl shadow-2xl overflow-hidden">
        {/* ヘッダ */}
        <div className={`px-6 py-5 ${isFsi ? 'bg-indigo-600' : 'bg-amber-500'}`}>
          <div className="flex items-start justify-between gap-3">
            <div>
              <div className="flex items-center gap-2 mb-2 flex-wrap">
                <span className="inline-block text-[11px] font-bold bg-white/20 text-white px-2.5 py-0.5 rounded-full">
                  {incident.discovery_type}
                </span>
                <RiskBadge riskLevelId={incident.risk_level_id} />
              </div>
              <p className="text-white/70 text-xs">{incident.discovery_date} 発見</p>
            </div>
            <button
              onClick={onClose}
              className="mt-1 w-7 h-7 flex items-center justify-center rounded-full bg-white/20 hover:bg-white/30 transition-colors flex-shrink-0"
            >
              <X size={14} color="white" />
            </button>
          </div>
        </div>

        {/* 本文 */}
        <div className="px-6 py-5 space-y-4 max-h-[60vh] overflow-y-auto">
          {/* メタ情報 */}
          <div className="grid grid-cols-2 gap-3">
            <div className="bg-slate-50 rounded-xl p-3">
              <p className="text-[10px] font-bold text-slate-400 uppercase tracking-wide mb-1">センター</p>
              <p className="text-sm font-semibold text-slate-700">{center?.name ?? '—'}</p>
            </div>
            <div className="bg-slate-50 rounded-xl p-3">
              <p className="text-[10px] font-bold text-slate-400 uppercase tracking-wide mb-1">報告者</p>
              <p className="text-sm font-semibold text-slate-700">{user?.name ?? '—'}</p>
            </div>
            <div className="bg-slate-50 rounded-xl p-3">
              <p className="text-[10px] font-bold text-slate-400 uppercase tracking-wide mb-1">ハザード</p>
              <p className="text-sm font-semibold text-slate-700">{hazard?.name ?? '—'}</p>
            </div>
            <div className="bg-slate-50 rounded-xl p-3">
              <p className="text-[10px] font-bold text-slate-400 uppercase tracking-wide mb-1">想定ケガ</p>
              <p className="text-sm font-semibold text-slate-700">{injury?.name ?? '—'}</p>
            </div>
            <div className="bg-slate-50 rounded-xl p-3 col-span-2">
              <p className="text-[10px] font-bold text-slate-400 uppercase tracking-wide mb-1.5">リスクレベル</p>
              <RiskBadge riskLevelId={incident.risk_level_id} size="md" />
            </div>
          </div>

          {/* 内容 */}
          <div>
            <p className="text-[10px] font-bold text-slate-400 uppercase tracking-wide mb-2">具体的な内容・状況</p>
            <p className="text-sm text-slate-700 leading-relaxed bg-slate-50 rounded-xl p-4">
              {incident.content}
            </p>
          </div>

          {/* FSI紐付け */}
          {incident.check_result_id && (
            <div className="flex items-center gap-2 text-xs text-indigo-600 bg-indigo-50 rounded-xl px-4 py-2.5">
              <AlertCircle size={13} />
              <span>FSI チェック結果 #{incident.check_result_id} に紐付き</span>
            </div>
          )}

          {/* ID */}
          <p className="text-[10px] text-slate-400 text-right">インシデント ID: {incident.id}　報告日時: {incident.created_at.replace('T', ' ').slice(0, 16)}</p>
        </div>
      </div>
    </div>
  );
};

// =============================================================
// AdminIncidentList — メイン画面
// =============================================================

const AdminIncidentList = ({ appData }) => {
  const {
    AlertTriangle, ChevronRight, X,
    Building2, AlertCircle,
  } = window.LucideReact;

  const [centerFilter,  setCenterFilter]  = useStateIL('all');
  const [typeFilter,    setTypeFilter]    = useStateIL('all');
  const [hazardFilter,  setHazardFilter]  = useStateIL('all');
  const [injuryFilter,  setInjuryFilter]  = useStateIL('all');
  const [riskFilter,    setRiskFilter]    = useStateIL('all');
  const [selectedId,    setSelectedId]    = useStateIL(null);

  const incidents = useMemoIL(() => appData.incidentReports || [], [appData.incidentReports]);

  // ─── サマリ集計 ─────────────────────────────────────────
  const statsData = useMemoIL(() => {
    const cutoff = new Date();
    cutoff.setDate(cutoff.getDate() - 30);
    const cutoffStr = cutoff.toISOString().split('T')[0];
    return {
      total:   incidents.length,
      fsi:     incidents.filter(i => i.discovery_type === 'FSI').length,
      hiyari:  incidents.filter(i => i.discovery_type === 'ヒヤリハット').length,
      recent:  incidents.filter(i => i.discovery_date >= cutoffStr).length,
    };
  }, [incidents]);

  // ─── ハザード別集計 ─────────────────────────────────────
  const hazardChartData = useMemoIL(() => {
    const counts = {};
    incidents.forEach(inc => {
      counts[inc.hazard_id] = (counts[inc.hazard_id] || 0) + 1;
    });
    return (window.MASTER_HAZARDS || [])
      .map(h => ({ hazard: h, count: counts[h.id] || 0 }))
      .filter(d => d.count > 0)
      .sort((a, b) => b.count - a.count);
  }, [incidents]);

  // ─── 月別推移（直近12ヶ月） ──────────────────────────────
  const monthlyData = useMemoIL(() => {
    const months = [];
    const now = new Date();
    for (let i = 11; i >= 0; i--) {
      const d     = new Date(now.getFullYear(), now.getMonth() - i, 1);
      const key   = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
      const label = `${d.getMonth() + 1}月`;
      const fsi    = incidents.filter(inc => inc.discovery_type === 'FSI'        && inc.discovery_date.startsWith(key)).length;
      const hiyari = incidents.filter(inc => inc.discovery_type === 'ヒヤリハット' && inc.discovery_date.startsWith(key)).length;
      months.push({ key, label, fsi, hiyari });
    }
    return months;
  }, [incidents]);

  // ─── フィルタ済みリスト ──────────────────────────────────
  const filtered = useMemoIL(() => {
    return incidents.filter(inc => {
      if (centerFilter !== 'all' && inc.center_id !== parseInt(centerFilter)) return false;
      if (typeFilter   !== 'all' && inc.discovery_type !== typeFilter)         return false;
      if (hazardFilter !== 'all' && inc.hazard_id      !== parseInt(hazardFilter)) return false;
      if (injuryFilter !== 'all' && inc.injury_type_id !== parseInt(injuryFilter)) return false;
      if (riskFilter   !== 'all' && inc.risk_level_id  !== parseInt(riskFilter))   return false;
      return true;
    }).sort((a, b) => b.discovery_date.localeCompare(a.discovery_date));
  }, [incidents, centerFilter, typeFilter, hazardFilter, injuryFilter, riskFilter]);

  const activeFilterCount = [centerFilter, typeFilter, hazardFilter, injuryFilter, riskFilter]
    .filter(v => v !== 'all').length;

  const clearFilters = () => {
    setCenterFilter('all'); setTypeFilter('all');
    setHazardFilter('all'); setInjuryFilter('all');
    setRiskFilter('all');
  };

  // ─── リスクレベル別件数 ──────────────────────────────────
  const riskCounts = useMemoIL(() => {
    const map = {};
    incidents.forEach(inc => { map[inc.risk_level_id] = (map[inc.risk_level_id] || 0) + 1; });
    return map;
  }, [incidents]);

  // ─── ヘルパー ────────────────────────────────────────────
  const getCenter     = id => (window.MASTER_CENTERS      || []).find(c => c.id === id);
  const getUser       = id => (window.MASTER_USERS        || []).find(u => u.id === id);
  const getHazard     = id => (window.MASTER_HAZARDS      || []).find(h => h.id === id);
  const getInjuryType = id => (window.MASTER_INJURY_TYPES || []).find(i => i.id === id);

  const selectedIncident = selectedId ? incidents.find(i => i.id === selectedId) : null;

  const selectStyle = 'text-xs border border-slate-200 rounded-lg px-3 py-1.5 bg-white outline-none focus:ring-2 focus:ring-indigo-300 text-slate-600';

  return (
    <div className="p-6 max-w-5xl space-y-6">

      {/* ヘッダ */}
      <div className="flex items-start justify-between flex-wrap gap-3">
        <div>
          <h1 className="text-xl font-bold text-slate-800">ヒヤリハット一覧</h1>
          <p className="text-sm text-slate-500 mt-0.5">インシデント（ヒヤリハット・FSI 発見 NG）の記録・集計</p>
        </div>
      </div>

      {/* サマリカード */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        {[
          { label: '総インシデント件数',  val: statsData.total,  unit: '件', bg: '#eef2ff', ic: '#6366f1' },
          { label: 'FSI 発見',            val: statsData.fsi,    unit: '件', bg: '#ede9fe', ic: '#7c3aed' },
          { label: 'ヒヤリハット',         val: statsData.hiyari, unit: '件', bg: '#fffbeb', ic: '#d97706' },
          { label: '直近 30 日',           val: statsData.recent, unit: '件', bg: statsData.recent > 0 ? '#fef2f2' : '#f0fdf4', ic: statsData.recent > 0 ? '#ef4444' : '#22c55e' },
        ].map(({ label, val, unit, bg, ic }) => (
          <div key={label} className="bg-white rounded-2xl border border-slate-200 p-4">
            <div className="w-9 h-9 rounded-xl flex items-center justify-center mb-3 flex-shrink-0" style={{ backgroundColor: bg }}>
              <AlertTriangle size={18} style={{ color: ic }} />
            </div>
            <p className="text-2xl font-bold text-slate-800 leading-none">
              {val}<span className="text-sm font-normal text-slate-500 ml-1">{unit}</span>
            </p>
            <p className="text-xs text-slate-400 mt-1.5 leading-tight">{label}</p>
          </div>
        ))}
      </div>

      {/* リスクレベル分布帯 */}
      <div className="bg-white rounded-2xl border border-slate-200 px-5 py-3.5">
        <div className="flex items-center gap-2.5 flex-wrap">
          <span className="text-xs font-bold text-slate-500 flex-shrink-0">リスクレベル別</span>
          {(window.MASTER_RISK_LEVELS || []).map(rl => {
            const count = riskCounts[rl.id] || 0;
            if (count === 0) return null;
            const isActive = riskFilter === String(rl.id);
            return (
              <button
                key={rl.id}
                onClick={() => setRiskFilter(isActive ? 'all' : String(rl.id))}
                className="flex items-center gap-1.5 rounded-full text-white font-bold transition-all"
                style={{
                  backgroundColor: rl.color,
                  fontSize: 11,
                  padding: '3px 10px',
                  opacity: riskFilter !== 'all' && !isActive ? 0.35 : 1,
                  transform: isActive ? 'scale(1.08)' : 'scale(1)',
                  boxShadow: isActive ? `0 0 0 2px white, 0 0 0 3.5px ${rl.color}` : 'none',
                }}
              >
                {rl.name}
                <span className="bg-white/30 rounded-full px-1.5 text-[10px] font-bold">{count}</span>
              </button>
            );
          })}
          {riskFilter !== 'all' && (
            <button
              onClick={() => setRiskFilter('all')}
              className="ml-auto text-xs text-slate-400 hover:text-slate-600 transition-colors flex-shrink-0"
            >
              <X size={11} className="inline mr-0.5" />絞り込み解除
            </button>
          )}
        </div>
      </div>

      {/* チャートセクション */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        {/* ハザード別件数 */}
        <div className="bg-white rounded-2xl border border-slate-200 p-5">
          <h2 className="text-sm font-bold text-slate-700 mb-4">ハザード別件数</h2>
          {hazardChartData.length > 0
            ? <HazardBarChart data={hazardChartData} />
            : <p className="text-xs text-slate-400 text-center py-6">データなし</p>
          }
        </div>

        {/* 月別推移 */}
        <div className="bg-white rounded-2xl border border-slate-200 p-5">
          <div className="flex items-center justify-between mb-4 flex-wrap gap-2">
            <h2 className="text-sm font-bold text-slate-700">月別推移（直近 12 ヶ月）</h2>
            <div className="flex items-center gap-3 text-[10px] text-slate-400">
              <span className="flex items-center gap-1"><span className="inline-block w-2 h-2 rounded-sm bg-indigo-500 flex-shrink-0" />FSI</span>
              <span className="flex items-center gap-1"><span className="inline-block w-2 h-2 rounded-sm bg-amber-400 flex-shrink-0" />ヒヤリハット</span>
            </div>
          </div>
          <IncidentMonthChart data={monthlyData} />
        </div>
      </div>

      {/* リスクアセスメントチャート */}
      <RiskAssessmentChart incidents={incidents} />

      {/* フィルタ + テーブル */}
      <div className="bg-white rounded-2xl border border-slate-200 overflow-hidden">

        {/* フィルタバー */}
        <div className="px-5 py-3.5 border-b border-slate-100 flex flex-wrap items-center gap-2">
          <span className="text-xs text-slate-400 flex-shrink-0">▼</span>
          <span className="text-xs font-bold text-slate-500 mr-1">絞り込み</span>

          <select value={centerFilter} onChange={e => setCenterFilter(e.target.value)} className={selectStyle}>
            <option value="all">全センター</option>
            {(window.MASTER_CENTERS || []).map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
          </select>

          <select value={typeFilter} onChange={e => setTypeFilter(e.target.value)} className={selectStyle}>
            <option value="all">発見区分：全て</option>
            <option value="FSI">FSI</option>
            <option value="ヒヤリハット">ヒヤリハット</option>
          </select>

          <select value={hazardFilter} onChange={e => setHazardFilter(e.target.value)} className={selectStyle}>
            <option value="all">ハザード：全て</option>
            {(window.MASTER_HAZARDS || []).map(h => <option key={h.id} value={h.id}>{h.name}</option>)}
          </select>

          <select value={injuryFilter} onChange={e => setInjuryFilter(e.target.value)} className={selectStyle}>
            <option value="all">ケガ：全て</option>
            {(window.MASTER_INJURY_TYPES || []).map(i => <option key={i.id} value={i.id}>{i.name}</option>)}
          </select>

          {activeFilterCount > 0 && (
            <button
              onClick={clearFilters}
              className="flex items-center gap-1 text-xs text-red-500 hover:text-red-700 ml-1 transition-colors"
            >
              <X size={11} />クリア
            </button>
          )}

          <span className="ml-auto text-xs text-slate-400 flex-shrink-0">
            {filtered.length} 件 / {incidents.length} 件
          </span>
        </div>

        {/* テーブル */}
        <div className="overflow-x-auto">
          <table className="w-full text-sm min-w-[700px]">
            <thead>
              <tr className="border-b border-slate-100 text-[11px] font-bold text-slate-500 bg-slate-50/60">
                <th className="text-left px-5 py-3">発見日</th>
                <th className="text-left px-3 py-3">発見区分</th>
                <th className="text-left px-3 py-3">センター</th>
                <th className="text-left px-3 py-3">ハザード</th>
                <th className="text-left px-3 py-3">想定ケガ</th>
                <th className="text-left px-3 py-3">リスク</th>
                <th className="text-left px-4 py-3">内容</th>
                <th className="text-left px-3 py-3">報告者</th>
                <th className="px-3 py-3 w-8"></th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {filtered.length === 0 && (
                <tr>
                  <td colSpan={9} className="text-center py-12 text-slate-400 text-sm">
                    該当するインシデントが見つかりません
                  </td>
                </tr>
              )}
              {filtered.map(inc => {
                const center  = getCenter(inc.center_id);
                const user    = getUser(inc.reported_by);
                const hazard  = getHazard(inc.hazard_id);
                const injury  = getInjuryType(inc.injury_type_id);
                const isFsi   = inc.discovery_type === 'FSI';
                return (
                  <tr
                    key={inc.id}
                    onClick={() => setSelectedId(inc.id)}
                    className="hover:bg-indigo-50/40 transition-colors cursor-pointer"
                  >
                    <td className="px-5 py-3 text-xs font-mono text-slate-500 whitespace-nowrap">{inc.discovery_date}</td>
                    <td className="px-3 py-3 whitespace-nowrap">
                      <span className={`text-[10px] font-bold px-2 py-0.5 rounded-full ${
                        isFsi ? 'bg-indigo-100 text-indigo-700' : 'bg-amber-100 text-amber-700'
                      }`}>
                        {inc.discovery_type}
                      </span>
                    </td>
                    <td className="px-3 py-3 text-xs text-slate-600 whitespace-nowrap">{center?.name ?? '—'}</td>
                    <td className="px-3 py-3 text-xs text-slate-700 whitespace-nowrap max-w-[140px] truncate">{hazard?.name ?? '—'}</td>
                    <td className="px-3 py-3 text-xs text-slate-600 whitespace-nowrap">{injury?.name ?? '—'}</td>
                    <td className="px-3 py-3 whitespace-nowrap">
                      <RiskBadge riskLevelId={inc.risk_level_id} />
                    </td>
                    <td className="px-4 py-3 text-xs text-slate-600 max-w-[220px]">
                      <span className="line-clamp-2 leading-snug">{inc.content}</span>
                    </td>
                    <td className="px-3 py-3 text-xs text-slate-500 whitespace-nowrap">{user?.name ?? '—'}</td>
                    <td className="px-3 py-3">
                      <ChevronRight size={13} className="text-slate-300" />
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>

      {/* 詳細モーダル */}
      {selectedIncident && (
        <IncidentDetailModal
          incident={selectedIncident}
          onClose={() => setSelectedId(null)}
        />
      )}
    </div>
  );
};

Object.assign(window, { AdminIncidentList, IncidentDetailModal, HazardBarChart, IncidentMonthChart, RiskAssessmentChart });
