/* ============================================================
   監査ログ（管理者のみ）：全案件の操作履歴（case_logs）を一元表示・検索・CSV出力
   権限 viewAuditLog（既定＝管理者のみ）で app.jsx / shell.jsx が閘門。ここでも二重防御。
   ============================================================ */
function AuditLogScreen() {
  const { logs, navigate, can } = useStore();
  const D = window.APP_DATA;
  const isMobile = useIsMobile();
  const [q, setQ] = React.useState('');
  const [userF, setUserF] = React.useState('all');
  const [typeF, setTypeF] = React.useState('all');
  const [days, setDays] = React.useState('30'); // '7' | '30' | '90' | 'all'
  const [page, setPage] = useUrlPage([q, userF, typeF, days]);

  if (!can('viewAuditLog')) return <Page title={t('page.audit')}><div style={{ padding: '48px 0', textAlign: 'center', color: '#9aa1ab', fontSize: 13 }}>{t('audit.noPerm')}</div></Page>;

  // 種別メタ（色・ラベル）。未知の type はそのまま表示
  const typeMeta = {
    status: { get label(){return window.t("apo.statusFilter");}, color: '#2563eb', bg: '#e8f0fe' },
    assign: { get label(){return window.t("cases.col.owner");}, color: '#7c3aed', bg: '#f1e9fd' },
    rank: { get label(){return window.t("cases.col.rank");}, color: '#d97706', bg: '#fdf0db' },
    meeting: { get label(){return window.t("extra.meetings.label");}, color: '#0891b2', bg: '#e0f4f8' },
    mail: { get label(){return window.t("cases.mail");}, color: '#4a5af0', bg: '#eef0fe' },
    note: { get label(){return window.t("cd.memo");}, color: '#6b7280', bg: '#eef0f3' },
  };
  const tm = (ty) => typeMeta[ty] || { label: ty || '—', color: '#6b7280', bg: '#eef0f3' };
  const caseName = (cid) => { const k = D.caseById && D.caseById(cid); if (!k) return { title: t('audit.deletedCase'), company: '' }; const cu = D.customer(k.customerId); return { title: k.title || '', company: cu ? (cu.shortName || cu.company || '') : '' }; };
  const uname = (id) => { const u = D.user(id); return u ? (u.name || id) : t('audit.unknownUser'); };

  const users = D.users || [];
  const allTypes = Array.from(new Set((logs || []).map(l => l.type).filter(Boolean)));
  const cutoff = days === 'all' ? '' : (() => { const d = new Date(); d.setDate(d.getDate() - Number(days)); const p = (n) => String(n).padStart(2, '0'); return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`; })();

  let rows = (logs || []).filter(l => {
    if (userF !== 'all' && l.userId !== userF) return false;
    if (typeF !== 'all' && l.type !== typeF) return false;
    if (cutoff && (l.at || '').slice(0, 10) < cutoff) return false;
    if (q) { const cn = caseName(l.caseId); const hay = (l.text || '') + uname(l.userId) + cn.company + cn.title; if (!hay.includes(q)) return false; }
    return true;
  }).sort((a, b) => (b.at || '').localeCompare(a.at || ''));

  const PER = 50;
  const totalPages = Math.max(1, Math.ceil(rows.length / PER));
  const safePage = Math.min(page, totalPages);
  syncUrlPage(safePage);
  const pageRows = rows.slice((safePage - 1) * PER, safePage * PER);

  const selStyle = { border: '1px solid #e2e5ea', borderRadius: 8, padding: '7px 10px', fontSize: 12.5, fontFamily: 'inherit', color: '#3b414b', background: '#fff' };
  const GRID = '150px 68px 148px 1fr 210px';

  return (
    <Page title={t('page.audit')} right={(
      <Button variant="default" icon="download" onClick={() => {
        csvDownload('audit-' + today() + '.csv', ['日時', '種別', '担当者', '内容', '会社', '案件'],
          rows.map(l => { const cn = caseName(l.caseId); return [fmtDateTime(l.at), tm(l.type).label, uname(l.userId), l.text || '', cn.company, cn.title]; }));
      }}>{t('btn.exportCsv')}</Button>
    )}>
      {/* フィルタ */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 16, flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, background: '#fff', border: '1px solid #e2e5ea', borderRadius: 8, padding: '7px 11px', width: isMobile ? '100%' : 260 }}>
          <Icon name="search" size={15} stroke={2} style={{ color: '#9aa1ab' }} />
          <input value={q} onChange={(e) => setQ(e.target.value)} placeholder={t('audit.searchPlaceholder')} style={{ border: 'none', outline: 'none', fontSize: 13, width: '100%', fontFamily: 'inherit', background: 'transparent' }} />
        </div>
        <select value={userF} onChange={(e) => setUserF(e.target.value)} style={selStyle}>
          <option value="all">{t('audit.allUsers')}</option>
          {users.map(u => <option key={u.id} value={u.id}>{u.name}</option>)}
        </select>
        <select value={typeF} onChange={(e) => setTypeF(e.target.value)} style={selStyle}>
          <option value="all">{t('audit.allTypes')}</option>
          {allTypes.map(ty => <option key={ty} value={ty}>{tm(ty).label}</option>)}
        </select>
        <select value={days} onChange={(e) => setDays(e.target.value)} style={selStyle}>
          <option value="7">{t('audit.days', { n: 7 })}</option>
          <option value="30">{t('audit.days', { n: 30 })}</option>
          <option value="90">{t('audit.days', { n: 90 })}</option>
          <option value="all">{t('audit.allPeriod')}</option>
        </select>
        <div style={{ marginLeft: 'auto', fontSize: 12.5, color: '#9aa1ab' }}>{rows.length} {t('unit.count')}</div>
      </div>

      {isMobile ? (
        <div style={{ display: 'grid', gap: 10 }}>
          {pageRows.map(l => { const cn = caseName(l.caseId); const m = tm(l.type); const u = D.user(l.userId); return (
            <div key={l.id} onClick={() => navigate('case', l.caseId)} className="lift" style={{ background: '#fff', border: '1px solid #ecedf0', borderRadius: 12, padding: 12, cursor: 'pointer', boxShadow: '0 1px 2px rgba(20,22,40,.04)' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                <span style={{ fontSize: 10.5, fontWeight: 700, color: m.color, background: m.bg, padding: '1px 7px', borderRadius: 999 }}>{m.label}</span>
                <span style={{ fontSize: 11.5, color: '#9aa1ab', marginLeft: 'auto', fontFamily: 'var(--mono)' }}>{fmtDateTime(l.at)}</span>
              </div>
              <div style={{ fontSize: 13, color: '#1f2430', lineHeight: 1.5 }}>{l.text}</div>
              <div style={{ fontSize: 11.5, color: '#9aa1ab', marginTop: 6, display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 }}>
                {u && <Avatar user={u} size={16} />}<span>{uname(l.userId)}</span><span>·</span><span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{cn.company} {cn.title}</span>
              </div>
            </div>
          ); })}
          {rows.length === 0 && <div style={{ padding: '40px 0', textAlign: 'center', color: '#9aa1ab', fontSize: 13 }}>{t('audit.empty')}</div>}
        </div>
      ) : (
        <div style={{ background: '#fff', border: '1px solid #ecedf0', borderRadius: 12, overflow: 'hidden', boxShadow: '0 1px 2px rgba(20,22,40,.04)' }}>
          <div style={{ overflowX: 'auto' }}>
            <div style={{ display: 'grid', gridTemplateColumns: GRID, padding: '11px 16px', borderBottom: '1px solid #f0f1f4', fontSize: 12, fontWeight: 600, color: '#9aa1ab', letterSpacing: '.02em', minWidth: 720 }}>
              <div>{t('audit.col.time')}</div><div>{t('audit.col.type')}</div><div>{t('audit.col.user')}</div><div>{t('audit.col.text')}</div><div>{t('audit.col.case')}</div>
            </div>
            {pageRows.map((l, i) => { const cn = caseName(l.caseId); const m = tm(l.type); const u = D.user(l.userId); return (
              <div key={l.id} className="case-row" onClick={() => navigate('case', l.caseId)} style={{ display: 'grid', gridTemplateColumns: GRID, padding: '10px 16px', alignItems: 'center', borderBottom: i === pageRows.length - 1 ? 'none' : '1px solid #f4f5f7', cursor: 'pointer', minWidth: 720 }}>
                <div style={{ fontSize: 12, color: '#7b828d', fontFamily: 'var(--mono)', whiteSpace: 'nowrap' }}>{fmtDateTime(l.at)}</div>
                <div><span style={{ fontSize: 10.5, fontWeight: 700, color: m.color, background: m.bg, padding: '1px 7px', borderRadius: 999, whiteSpace: 'nowrap' }}>{m.label}</span></div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 }}>{u && <Avatar user={u} size={18} />}<span style={{ fontSize: 12.5, color: '#3b414b', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{uname(l.userId)}</span></div>
                <div style={{ fontSize: 12.5, color: '#1f2430', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', paddingRight: 10 }}>{l.text}</div>
                <div style={{ fontSize: 12, color: '#4a5af0', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{cn.company} <span style={{ color: '#9aa1ab' }}>{cn.title}</span></div>
              </div>
            ); })}
            {rows.length === 0 && <div style={{ padding: '44px 0', textAlign: 'center', color: '#9aa1ab', fontSize: 13 }}>{t('audit.empty')}</div>}
          </div>
        </div>
      )}

      {totalPages > 1 && (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 12, marginTop: 16 }}>
          <Button size="sm" variant="default" icon="chevronLeft" onClick={() => setPage(p => Math.max(1, p - 1))} disabled={safePage === 1}>{t('btn.prev')}</Button>
          <span style={{ fontSize: 12.5, color: '#7b828d', fontWeight: 600 }}>{safePage} / {totalPages}</span>
          <Button size="sm" variant="default" iconRight="chevronRight" onClick={() => setPage(p => Math.min(totalPages, p + 1))} disabled={safePage === totalPages}>{t('btn.next')}</Button>
        </div>
      )}
    </Page>
  );
}

Object.assign(window, { AuditLogScreen });
