// ===== 历史记录页面 =====
const { useState: useStateHP, useMemo: useMemoHP } = React;

function HistoryPage({ device, onBack, onViewRecord }) {
  const [filter, setFilter] = useStateHP('all');
  const [selectedRecord, setSelectedRecord] = useStateHP(null);

  const records = useMemoHP(() => {
    const list = getDeviceRecords(device.id);
    if (filter === 'all') return list;
    return list.filter(r => r.workType === filter);
  }, [device.id, filter]);

  const formatDate = (dateStr) => {
    const d = new Date(dateStr);
    return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
  };

  if (selectedRecord) {
    return (
      <RecordDetail record={selectedRecord} onBack={() => setSelectedRecord(null)} />
    );
  }

  return (
    <div className="page">
      <div className="hazard-stripe" />

      <div className="page-header" style={{ paddingTop: 12 }}>
        <div className="page-header-content">
          <button className="back-btn" onClick={onBack}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
              <path d="M15 18l-6-6 6-6" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </button>
          <h1 style={{ fontSize: 17 }}>历史记录</h1>
          <div style={{ width: 40 }} />
        </div>
      </div>

      <div className="page-body">
        {/* 设备信息条 */}
        <div className="card" style={{ marginBottom: '16px', padding: '12px 14px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
            <div style={{
              width: '36px',
              height: '36px',
              borderRadius: '8px',
              background: 'rgba(255,209,0,0.15)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              flexShrink: 0,
            }}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
                <path d="M20 7h-3V3H7v4H4v11h16V7zM9 5h6v2H9V5z" fill="var(--safety-yellow)" />
              </svg>
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{
                fontWeight: 700,
                fontSize: '14px',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
              }}>
                {device.name}
              </div>
              <div style={{ fontSize: '12px', color: 'var(--text-muted)' }}>
                共 {records.length} 条记录
              </div>
            </div>
          </div>
        </div>

        {/* 筛选 */}
        <div style={{ display: 'flex', gap: '8px', marginBottom: '16px', overflowX: 'auto', paddingBottom: '4px' }}>
          {[
            { id: 'all', label: '全部' },
            ...WORK_TYPES.map(t => ({ id: t.id, label: t.name })),
          ].map(f => (
            <button
              key={f.id}
              onClick={() => setFilter(f.id)}
              style={{
                padding: '6px 14px',
                background: filter === f.id ? 'var(--safety-yellow)' : 'var(--industrial-gray)',
                color: filter === f.id ? 'var(--industrial-darker)' : 'var(--text-secondary)',
                border: 'none',
                borderRadius: '8px',
                fontSize: '13px',
                fontWeight: filter === f.id ? 700 : 500,
                cursor: 'pointer',
                fontFamily: 'inherit',
                whiteSpace: 'nowrap',
                flexShrink: 0,
              }}
            >
              {f.label}
            </button>
          ))}
        </div>

        {/* 记录列表 */}
        {records.length > 0 ? (
          <div>
            {records.map(record => (
              <div
                key={record.id}
                className="list-item"
                onClick={() => setSelectedRecord(record)}
              >
                <div className="list-item-icon" style={{
                  background: record.aCycleCompleted ? 'rgba(46,125,50,0.15)' : 'rgba(198,40,40,0.15)',
                }}>
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                    <path d="M6 10V7a6 6 0 1 1 12 0v3" stroke={record.aCycleCompleted ? '#4CAF50' : '#EF5350'} strokeWidth="2" strokeLinecap="round" />
                    <rect x="4" y="10" width="16" height="11" rx="2" fill={record.aCycleCompleted ? '#4CAF50' : '#EF5350'} opacity="0.8" />
                  </svg>
                </div>
                <div className="list-item-content">
                  <div className="list-item-title">{record.workTypeName}</div>
                  <div className="list-item-subtitle">
                    {record.operator} · {formatDate(record.createdAt)}
                  </div>
                </div>
                <div className="list-item-arrow">
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                    <path d="M9 18l6-6-6-6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="empty-state">
            <svg className="empty-state-icon" viewBox="0 0 24 24" fill="none">
              <rect x="3" y="4" width="18" height="16" rx="2" stroke="currentColor" strokeWidth="2" />
              <path d="M7 9h10M7 13h6M7 17h8" stroke="currentColor" strokeWidth="2" strokeLinecap="round" opacity="0.5" />
            </svg>
            <p className="empty-state-text">暂无作业记录</p>
            <p className="empty-state-desc">该设备尚未产生LOTO作业记录</p>
          </div>
        )}
      </div>
    </div>
  );
}

function RecordDetail({ record, onBack }) {
  const formatDate = (dateStr) => {
    const d = new Date(dateStr);
    return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
  };

  const [activePhoto, setActivePhoto] = useStateHP(null);

  return (
    <div className="page">
      <div className="hazard-stripe" />

      <div className="page-header" style={{ paddingTop: 12 }}>
        <div className="page-header-content">
          <button className="back-btn" onClick={onBack}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
              <path d="M15 18l-6-6 6-6" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </button>
          <h1 style={{ fontSize: 16 }}>记录详情</h1>
          <div style={{ width: 40 }} />
        </div>
      </div>

      <div className="page-body">
        {/* 概览卡 */}
        <div className="card" style={{ marginBottom: '16px' }}>
          <div style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            marginBottom: '12px',
            paddingBottom: '12px',
            borderBottom: '1px solid var(--border)',
          }}>
            <div>
              <div style={{ fontSize: '17px', fontWeight: 700 }}>{record.workTypeName}</div>
              <div style={{ fontSize: '12px', color: 'var(--text-muted)', marginTop: '2px' }}>
                {record.id}
              </div>
            </div>
            <span className="status-badge status-completed">已完成</span>
          </div>

          <div style={{ display: 'grid', gap: '8px' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <span style={{ color: 'var(--text-muted)', fontSize: '13px' }}>设备</span>
              <span style={{ fontWeight: 600, fontSize: '13px' }}>{record.deviceName}</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <span style={{ color: 'var(--text-muted)', fontSize: '13px' }}>作业时间</span>
              <span style={{ fontWeight: 600, fontSize: '13px' }}>{formatDate(record.createdAt)}</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <span style={{ color: 'var(--text-muted)', fontSize: '13px' }}>执行人</span>
              <span style={{ fontWeight: 600, fontSize: '13px' }}>{record.operator}</span>
            </div>
            {record.guardian && (
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ color: 'var(--text-muted)', fontSize: '13px' }}>监护人</span>
                <span style={{ fontWeight: 600, fontSize: '13px' }}>{record.guardian}</span>
              </div>
            )}
          </div>
        </div>

        {/* A循环 */}
        <div className="section-title">
          <span className="cycle-badge cycle-a" style={{ width: 22, height: 22, fontSize: 12 }}>A</span>
          能源锁定
          <span style={{ marginLeft: 'auto', fontSize: '12px', color: 'var(--success-light)', fontWeight: 600 }}>
            {record.energyLocks.filter(l => l.verified).length}/{record.energyLocks.length} 已验证
          </span>
        </div>

        <div style={{ marginBottom: '16px' }}>
          {record.energyLocks.map(l => (
            <div
              key={l.id}
              className={`lock-point-card ${l.verified ? 'verified' : l.locked ? 'unverified' : ''}`}
            >
              <div className="lock-point-header">
                <span className="lock-point-id">{l.id}</span>
                <span style={{
                  fontSize: '11px',
                  padding: '2px 6px',
                  borderRadius: '4px',
                  background: l.verified ? 'rgba(46,125,50,0.2)' : 'rgba(198,40,40,0.2)',
                  color: l.verified ? 'var(--success-light)' : 'var(--danger-light)',
                  fontWeight: 600,
                }}>
                  {l.verified ? '已验证' : l.locked ? '未验证' : '未锁定'}
                </span>
              </div>
              <div className="lock-point-detail">{l.control}</div>
            </div>
          ))}
        </div>

        {/* B循环 */}
        {record.bCycleEnabled && (
          <>
            <div className="section-title">
              <span className="cycle-badge cycle-b" style={{ width: 22, height: 22, fontSize: 12 }}>B</span>
              信号锁定
              <span style={{ marginLeft: 'auto', fontSize: '12px', color: 'var(--success-light)', fontWeight: 600 }}>
                {record.signalLocks.filter(l => l.verified).length}/{record.signalLocks.length} 已验证
              </span>
            </div>
            <div style={{ marginBottom: '16px' }}>
              {record.signalLocks.map(l => (
                <div
                  key={l.id}
                  className={`lock-point-card ${l.verified ? 'verified' : l.locked ? 'unverified' : ''}`}
                >
                  <div className="lock-point-header">
                    <span className="lock-point-id">{l.device}</span>
                    <span className="lock-point-tag tag-signal">{l.id}</span>
                  </div>
                  <div className="lock-point-detail">{l.control}</div>
                </div>
              ))}
            </div>
          </>
        )}

        {/* 照片 */}
        {record.photos && record.photos.length > 0 && (
          <>
            <div className="section-title">现场照片</div>
            <div style={{
              display: 'grid',
              gridTemplateColumns: 'repeat(3, 1fr)',
              gap: '6px',
              marginBottom: '16px',
            }}>
              {record.photos.map((p, i) => (
                <img
                  key={i}
                  src={p}
                  alt={`照片${i + 1}`}
                  onClick={() => setActivePhoto(p)}
                  style={{
                    aspectRatio: '1',
                    objectFit: 'cover',
                    borderRadius: '8px',
                    cursor: 'pointer',
                  }}
                />
              ))}
            </div>
          </>
        )}

        {/* 签名 */}
        <div className="section-title">签字确认</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px', marginBottom: '20px' }}>
          <div className="card" style={{ textAlign: 'center', padding: '12px' }}>
            <div style={{ fontSize: '12px', color: 'var(--text-muted)', marginBottom: '6px' }}>
              执行人
            </div>
            {record.operatorSig ? (
              <img src={record.operatorSig} alt="签名" style={{ height: '44px', width: 'auto' }} />
            ) : (
              <div style={{ color: 'var(--text-muted)', fontSize: '12px', padding: '10px 0' }}>无</div>
            )}
            <div style={{ fontSize: '12px', fontWeight: 600, marginTop: '6px' }}>{record.operator}</div>
          </div>
          <div className="card" style={{ textAlign: 'center', padding: '12px' }}>
            <div style={{ fontSize: '12px', color: 'var(--text-muted)', marginBottom: '6px' }}>
              监护人
            </div>
            {record.guardianSig ? (
              <img src={record.guardianSig} alt="签名" style={{ height: '44px', width: 'auto' }} />
            ) : (
              <div style={{ color: 'var(--text-muted)', fontSize: '12px', padding: '10px 0' }}>无</div>
            )}
            <div style={{ fontSize: '12px', fontWeight: 600, marginTop: '6px' }}>{record.guardian || '-'}</div>
          </div>
        </div>

        {record.remark && (
          <>
            <div className="section-title">备注</div>
            <div className="card">
              <p style={{ fontSize: '14px', lineHeight: 1.7, color: 'var(--text-secondary)' }}>
                {record.remark}
              </p>
            </div>
          </>
        )}
      </div>

      {/* 照片预览弹层 */}
      {activePhoto && (
        <div
          onClick={() => setActivePhoto(null)}
          style={{
            position: 'fixed',
            top: 0, left: 0, right: 0, bottom: 0,
            background: 'rgba(0,0,0,0.95)',
            zIndex: 1000,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          }}
        >
          <img src={activePhoto} alt="预览" style={{ maxWidth: '100%', maxHeight: '100%' }} />
          <div style={{
            position: 'absolute',
            top: '20px',
            right: '20px',
            color: 'white',
            fontSize: '24px',
            cursor: 'pointer',
          }}>
            ×
          </div>
        </div>
      )}
    </div>
  );
}

window.HistoryPage = HistoryPage;
