// =============================================================
// CheckHistory.jsx — チェック履歴一覧（マトリクス表示）+ 詳細
// =============================================================

const { useState: useStateH, useMemo: useMemoH } = React;
const {
  ArrowLeft, CheckCircle: CheckCircleH, XCircle,
  Clock: ClockH,
} = window.LucideReact;

// ─── 日付ユーティリティ ──────────────────────────────────────

const _days  = ['日', '月', '火', '水', '木', '金', '土'];
const fmtShortDate = (dateStr) => {
  const d = new Date(dateStr + 'T00:00:00');
  return `${d.getMonth() + 1}/${d.getDate()}`;
};
const fmtDayOfWeek = (dateStr) => {
  const d = new Date(dateStr + 'T00:00:00');
  return _days[d.getDay()];
};
const fmtLong = (dateStr) => {
  const d = new Date(dateStr + 'T00:00:00');
  return `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日（${_days[d.getDay()]}）`;
};
const fmtMonth = (mStr) => {
  const [y, m] = mStr.split('-');
  return `${y}年${parseInt(m)}月`;
};

// ─── マトリクス一覧 ──────────────────────────────────────────

const ITEM_COL_W = 176;
const DATE_COL_W = 72;

const CheckHistory = ({ appData, navigate }) => {

  const allRecords = useMemoH(() =>
    [...(appData.checkRecords || [])]
      .filter(r => r.user_id === 1)
      .sort((a, b) => a.check_date.localeCompare(b.check_date) || a.start_time.localeCompare(b.start_time)),
    [appData.checkRecords]
  );

  const months = useMemoH(() => {
    const set = new Set(allRecords.map(r => r.check_date.substring(0, 7)));
    return [...set].sort().reverse();
  }, [allRecords]);

  const [selectedMonth, setSelectedMonth] = useStateH(() => months[0] || '');

  const monthRecords = useMemoH(() =>
    allRecords.filter(r => r.check_date.startsWith(selectedMonth)),
    [allRecords, selectedMonth]
  );

  // { recordId: { itemId: 'OK'|'NG' } }
  const resultMap = useMemoH(() => {
    const map = {};
    for (const res of (appData.checkResults || [])) {
      if (!map[res.check_record_id]) map[res.check_record_id] = {};
      map[res.check_record_id][res.check_item_id] = res.result;
    }
    return map;
  }, [appData.checkResults]);

  // NG数 per record
  const ngMap = useMemoH(() => {
    const map = {};
    for (const rec of monthRecords) {
      const results = resultMap[rec.id] || {};
      map[rec.id] = Object.values(results).filter(r => r === 'NG').length;
    }
    return map;
  }, [monthRecords, resultMap]);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', minHeight: '100%' }}>

      {/* 月タブ */}
      <div style={{
        position: 'sticky', top: 0, background: '#fff',
        borderBottom: '1px solid #e2e8f0', zIndex: 30,
      }}>
        <div style={{
          display: 'flex', overflowX: 'auto', padding: '10px 14px', gap: 6,
          WebkitOverflowScrolling: 'touch',
        }}>
          {months.map(m => (
            <button
              key={m}
              onClick={() => setSelectedMonth(m)}
              style={{
                flexShrink: 0,
                padding: '5px 13px',
                borderRadius: 999,
                fontSize: 12,
                fontWeight: 600,
                border: 'none',
                cursor: 'pointer',
                transition: 'all 0.15s',
                background: selectedMonth === m ? '#4f46e5' : '#f1f5f9',
                color:      selectedMonth === m ? '#fff'    : '#64748b',
              }}
            >
              {fmtMonth(m)}
            </button>
          ))}
        </div>
      </div>

      {/* グリッド本体 */}
      {monthRecords.length === 0 ? (
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '64px 0', color: '#94a3b8', gap: 10 }}>
          <ClockH size={40} strokeWidth={1.2} />
          <p style={{ fontSize: 13, margin: 0 }}>この月のチェック記録はありません</p>
        </div>
      ) : (
        <div style={{ flex: 1, overflow: 'auto', WebkitOverflowScrolling: 'touch' }}>
          <table style={{ borderCollapse: 'separate', borderSpacing: 0, tableLayout: 'fixed', minWidth: ITEM_COL_W + DATE_COL_W * monthRecords.length }}>

            {/* ── ヘッダー行（日付） ── */}
            <thead>
              <tr>
                {/* 項目名ヘッダー（左上コーナー） */}
                <th style={{
                  width: ITEM_COL_W, minWidth: ITEM_COL_W,
                  position: 'sticky', left: 0, top: 0, zIndex: 40,
                  background: '#f8fafc',
                  borderBottom: '2px solid #e2e8f0',
                  borderRight: '2px solid #e2e8f0',
                  padding: '8px 10px',
                  textAlign: 'left',
                  fontSize: 10, fontWeight: 700, color: '#94a3b8',
                  letterSpacing: '0.04em',
                }}>
                  チェック項目
                </th>

                {/* 日付列ヘッダー */}
                {monthRecords.map(rec => {
                  const area = window.MASTER_AREAS.find(a => a.id === rec.area_id);
                  const ng   = ngMap[rec.id] || 0;
                  const dow  = fmtDayOfWeek(rec.check_date);
                  const dowColor = dow === '土' ? '#3b82f6' : dow === '日' ? '#ef4444' : '#94a3b8';
                  return (
                    <th
                      key={rec.id}
                      onClick={() => navigate('CHECK_HISTORY_DETAIL', { recordId: rec.id })}
                      style={{
                        width: DATE_COL_W, minWidth: DATE_COL_W,
                        position: 'sticky', top: 0, zIndex: 20,
                        background: '#f8fafc',
                        borderBottom: '2px solid #e2e8f0',
                        borderRight: '1px solid #e2e8f0',
                        padding: '6px 4px 7px',
                        textAlign: 'center',
                        cursor: 'pointer',
                        verticalAlign: 'top',
                      }}
                    >
                      <div style={{ fontSize: 14, fontWeight: 700, color: '#1e293b', lineHeight: 1.2 }}>
                        {fmtShortDate(rec.check_date)}
                      </div>
                      <div style={{ fontSize: 10, fontWeight: 600, color: dowColor, marginTop: 1 }}>
                        （{dow}）
                      </div>
                      <div style={{ fontSize: 9, color: '#94a3b8', marginTop: 3, lineHeight: 1.3, padding: '0 2px', wordBreak: 'keep-all' }}>
                        {area?.name}
                      </div>
                      <div style={{ fontSize: 9, color: '#94a3b8', marginTop: 1 }}>
                        {rec.start_time}
                      </div>
                      {ng > 0 ? (
                        <div style={{
                          marginTop: 4,
                          display: 'inline-block',
                          background: '#fee2e2', color: '#dc2626',
                          borderRadius: 4, padding: '1px 5px',
                          fontSize: 9, fontWeight: 700,
                        }}>
                          NG {ng}
                        </div>
                      ) : (
                        <div style={{
                          marginTop: 4,
                          display: 'inline-block',
                          background: '#dcfce7', color: '#16a34a',
                          borderRadius: 4, padding: '1px 5px',
                          fontSize: 9, fontWeight: 700,
                        }}>
                          異常なし
                        </div>
                      )}
                    </th>
                  );
                })}
              </tr>
            </thead>

            {/* ── データ行 ── */}
            <tbody>
              {window.MASTER_CHECK_CATEGORIES.map(cat => {
                const catItems = window.MASTER_CHECK_ITEMS.filter(i => i.category_id === cat.id);
                return (
                  <React.Fragment key={cat.id}>

                    {/* カテゴリ行 */}
                    <tr>
                      <td
                        colSpan={monthRecords.length + 1}
                        style={{
                          background: '#f1f5f9',
                          borderTop: '1px solid #e2e8f0',
                          borderBottom: '1px solid #e2e8f0',
                          padding: '4px 10px',
                          fontSize: 10, fontWeight: 700,
                          color: '#475569',
                          letterSpacing: '0.06em',
                          whiteSpace: 'nowrap',
                        }}
                      >
                        {cat.name}
                      </td>
                    </tr>

                    {/* 項目行 */}
                    {catItems.map((item, idx) => {
                      const rowBg = idx % 2 === 0 ? '#ffffff' : '#fafafa';
                      return (
                        <tr key={item.id}>

                          {/* 項目名（左スティッキー） */}
                          <td style={{
                            position: 'sticky', left: 0, zIndex: 10,
                            background: rowBg,
                            borderRight: '2px solid #e2e8f0',
                            borderBottom: '1px solid #f1f5f9',
                            padding: '7px 10px',
                            fontSize: 11, color: '#334155', lineHeight: 1.45,
                            width: ITEM_COL_W, minWidth: ITEM_COL_W, maxWidth: ITEM_COL_W,
                            wordBreak: 'break-all',
                          }}>
                            {item.name}
                          </td>

                          {/* 結果セル */}
                          {monthRecords.map(rec => {
                            const result = (resultMap[rec.id] || {})[item.id];
                            let cellBg, cellColor, symbol;
                            if (!result) {
                              cellBg = rowBg; cellColor = '#d1d5db'; symbol = '—';
                            } else if (result === 'OK') {
                              cellBg = '#f0fdf4'; cellColor = '#16a34a'; symbol = '✓';
                            } else {
                              cellBg = '#fff1f2'; cellColor = '#ef4444'; symbol = '✗';
                            }
                            return (
                              <td
                                key={rec.id}
                                onClick={() => result && navigate('CHECK_HISTORY_DETAIL', { recordId: rec.id })}
                                style={{
                                  background: cellBg,
                                  borderRight: '1px solid #f1f5f9',
                                  borderBottom: '1px solid #f1f5f9',
                                  textAlign: 'center',
                                  fontSize: result === 'NG' ? 15 : 14,
                                  fontWeight: result === 'NG' ? 700 : 400,
                                  color: cellColor,
                                  cursor: result ? 'pointer' : 'default',
                                  padding: '6px 0',
                                  transition: 'background 0.1s',
                                }}
                              >
                                {symbol}
                              </td>
                            );
                          })}
                        </tr>
                      );
                    })}
                  </React.Fragment>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
};

// ─── 詳細画面（変更なし） ────────────────────────────────────

const CheckHistoryDetail = ({ appData, navigate, screenParams }) => {

  const { recordId } = screenParams || {};
  const record = (appData.checkRecords || []).find(r => r.id === recordId);

  if (!record) {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '80px 0', gap: 12, color: '#94a3b8' }}>
        <p style={{ fontSize: 13, margin: 0 }}>レコードが見つかりません</p>
        <button
          onClick={() => navigate('CHECK_HISTORY')}
          style={{ color: '#4f46e5', fontSize: 13, fontWeight: 600, background: 'none', border: 'none', cursor: 'pointer' }}
        >← 履歴一覧に戻る</button>
      </div>
    );
  }

  const area    = window.MASTER_AREAS.find(a => a.id === record.area_id);
  const results = (appData.checkResults || []).filter(r => r.check_record_id === record.id);
  const ngCount = results.filter(r => r.result === 'NG').length;

  const byCategory = window.MASTER_CHECK_CATEGORIES.map(cat => {
    const catResults = results.filter(res => {
      const item = window.MASTER_CHECK_ITEMS.find(i => i.id === res.check_item_id);
      return item?.category_id === cat.id;
    });
    return catResults.length > 0 ? { category: cat, results: catResults } : null;
  }).filter(Boolean);

  return (
    <div style={{ minHeight: '100%' }}>

      {/* サブヘッダー */}
      <div style={{
        position: 'sticky', top: 0, background: '#fff',
        borderBottom: '1px solid #e2e8f0', zIndex: 10,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px' }}>
          <button
            onClick={() => navigate('CHECK_HISTORY')}
            style={{
              width: 32, height: 32, borderRadius: '50%',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              border: 'none', background: 'none', cursor: 'pointer', flexShrink: 0,
            }}
          >
            <ArrowLeft size={18} color="#475569" />
          </button>
          <div style={{ flex: 1, minWidth: 0 }}>
            <p style={{ margin: 0, fontWeight: 700, fontSize: 13, color: '#1e293b', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {fmtLong(record.check_date)}
            </p>
            <p style={{ margin: 0, fontSize: 11, color: '#94a3b8', marginTop: 1 }}>
              {area?.name}　{record.start_time} 開始
            </p>
          </div>
          <span style={{
            flexShrink: 0, fontSize: 11, fontWeight: 700,
            padding: '4px 10px', borderRadius: 999,
            background: ngCount > 0 ? '#fee2e2' : '#dcfce7',
            color:      ngCount > 0 ? '#dc2626' : '#16a34a',
          }}>
            {ngCount > 0 ? `NG ${ngCount}件` : '異常なし'}
          </span>
        </div>
      </div>

      {/* 結果一覧 */}
      <div style={{ padding: '14px 14px 24px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        {byCategory.map(({ category, results: catResults }) => (
          <div key={category.id} style={{
            background: '#fff', borderRadius: 16,
            border: '1px solid #e2e8f0', overflow: 'hidden',
          }}>
            <div style={{
              padding: '8px 14px', background: '#f8fafc',
              borderBottom: '1px solid #f1f5f9',
              fontSize: 11, fontWeight: 700, color: '#475569',
            }}>
              {category.name}
            </div>
            <div>
              {catResults.map((res, idx) => {
                const item     = window.MASTER_CHECK_ITEMS.find(i => i.id === res.check_item_id);
                const ngDetail = (appData.ngDetails || []).find(d => d.check_result_id === res.id);
                const isNg     = res.result === 'NG';
                return (
                  <div
                    key={res.id}
                    style={{
                      padding: '11px 14px',
                      borderTop: idx > 0 ? '1px solid #f1f5f9' : 'none',
                    }}
                  >
                    <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
                      <div style={{
                        flexShrink: 0, width: 22, height: 22, borderRadius: '50%',
                        background: isNg ? '#fee2e2' : '#dcfce7',
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        marginTop: 1,
                      }}>
                        {isNg
                          ? <XCircle size={13} color="#ef4444" />
                          : <CheckCircleH size={13} color="#22c55e" />
                        }
                      </div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <p style={{
                          margin: 0, fontSize: 13, lineHeight: 1.5,
                          fontWeight: isNg ? 600 : 400,
                          color: isNg ? '#dc2626' : '#334155',
                        }}>
                          {item?.name}
                        </p>
                        {isNg && ngDetail && (
                          <div style={{
                            marginTop: 8, padding: '10px 12px',
                            background: '#fff8f8', borderRadius: 10,
                            border: '1px solid #fecaca',
                          }}>
                            <p style={{ margin: 0, fontSize: 12, color: '#475569', lineHeight: 1.6 }}>
                              {ngDetail.comment}
                            </p>
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

Object.assign(window, { CheckHistory, CheckHistoryDetail });
