const { useState, useMemo } = React;

const COLORS = {
  blue: '#2b7fff',
  green: '#00c896',
  orange: '#ff9f1c',
  red: '#ff5a5a',
  purple: '#7c3aed',
  cyan: '#0ea5e9',
  pink: '#ff4d8d',
  bg: '#f5f7fa',
};

const BRAND_COLORS = {
  '鱼跃': COLORS.blue,
  '太一': COLORS.green,
  '优乐合': COLORS.orange,
};

const ICONS = {
  blood_pressure: '🩺',
  blood_glucose: '🩸',
  uric_acid: '🧪',
  ring: '💍',
  cgm: '📡',
  ecg: '❤️',
  watch: '⌚',
  pill_box: '💊',
};

const INITIAL_DEVICES = [
  { id: 1, brand: '鱼跃', name: '鱼跃血压仪', model: 'YE660D', type: 'blood_pressure', status: 'disconnected' },
  { id: 2, brand: '鱼跃', name: '鱼跃血糖仪', model: 'YE-8900', type: 'blood_glucose', status: 'unbound' },
  { id: 3, brand: '鱼跃', name: '鱼跃尿酸仪', model: 'YE-UA100', type: 'uric_acid', status: 'unbound' },
  { id: 4, brand: '鱼跃医疗', name: '鱼跃医疗智能戒指', model: 'SR10', type: 'ring', status: 'unbound' },
  { id: 5, brand: '鱼跃医疗', name: '鱼跃医疗动态血糖仪', model: 'CGM-S1', type: 'cgm', status: 'unbound' },
  { id: 6, brand: 'VivaLNK', name: '(VivaLNK)动态心电', model: 'ECG Patch', type: 'ecg', status: 'unbound' },
  { id: 7, brand: '研合', name: '研合智能手表', model: 'YH-W1', type: 'watch', status: 'connected' },
];

const MEMBERS = [
  { id: 'self', name: '李明', relation: '本人', age: 35, gender: '男', avatar: '👨' },
  { id: 'spouse', name: '张敏', relation: '配偶', age: 33, gender: '女', avatar: '👩' },
  { id: 'father', name: '李建国', relation: '父亲', age: 65, gender: '男', avatar: '👴' },
  { id: 'mother', name: '王芳', relation: '母亲', age: 63, gender: '女', avatar: '👵' },
  { id: 'child', name: '李小明', relation: '子女', age: 8, gender: '男', avatar: '👦' },
];

const HEALTH_ITEMS = {
  longTerm: [
    { key: 'dynamic_ecg', name: '动态心电', icon: '❤️', iconBg: '#ffe8ec', iconColor: '#ff4d6d', hint: '点击开始监测', hintColor: '#ff4d6d', sub: '支持长程监测', bluetooth: false },
    { key: 'dynamic_glucose', name: '动态血糖', icon: '📈', iconBg: '#fff4e5', iconColor: '#ff9f1c', hint: '点击开始监测', hintColor: '#ff9f1c', sub: '支持长程监测', bluetooth: false },
  ],
  instant: [
    { key: 'blood_pressure', name: '血压', icon: '🩺', iconBg: '#eef4ff', iconColor: '#2b7fff', value: '118/76', unit: 'mmHg', time: '今天 08:30', bluetooth: true },
    { key: 'blood_glucose', name: '血糖', icon: '🩸', iconBg: '#fff4e5', iconColor: '#ff9f1c', value: '5.6', unit: 'mmol/L', time: '今天 07:00', bluetooth: true },
    { key: 'spo2', name: '血氧', icon: '🫁', iconBg: '#eafff5', iconColor: '#00c896', value: '98', unit: '%', time: '昨天 22:10', bluetooth: true },
    { key: 'ecg', name: '心电', icon: '❤️', iconBg: '#ffe8ec', iconColor: '#ff4d6d', value: '正常窦律', unit: '', time: '3天前', bluetooth: true, valueColor: '#ff4d6d' },
  ],
};

function FamilySwitcher({ selectedMemberId, onSelect }) {
  return (
    <div className="family-bar">
      {MEMBERS.map(m => (
        <div
          key={m.id}
          className={`family-item ${selectedMemberId === m.id ? 'active' : ''}`}
          onClick={() => onSelect(m.id)}
        >
          <div className="family-avatar">{m.avatar}</div>
          <div className="family-name">{m.name}</div>
        </div>
      ))}
      <div className="family-add">+</div>
    </div>
  );
}

function StatusLabel({ status }) {
  if (status === 'connected') {
    return (
      <div className="device-status connected">
        <span className="device-status-dot"></span>
        <span>已连接</span>
      </div>
    );
  }
  if (status === 'disconnected') {
    return (
      <div className="device-status">
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" style={{ marginRight: 3 }}>
          <path d="M4.3 4.3l15.4 15.4M8.5 12.5l-3.4 3.4a6 6 0 0 1 8.5-8.5l-1.8 1.8M12 19l.01-.01M16.5 12.5l3.4-3.4a6 6 0 0 0-8.5 8.5l1.8-1.8M12 5l-.01.01" />
        </svg>
        <span>已断开</span>
      </div>
    );
  }
  return (
    <div className="device-status">
      <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor" style={{ marginRight: 3 }}>
        <path d="M12 2l2.4 7.2h7.6l-6 4.8 2.4 7.2-6-4.8-6 4.8 2.4-7.2-6-4.8h7.6z" />
      </svg>
      <span>未绑定</span>
    </div>
  );
}

function DeviceRow({ device, onBind, onDisconnect }) {
  const brandColor = BRAND_COLORS[device.brand.replace('医疗', '')] || COLORS.blue;
  const icon = ICONS[device.type] || '🔧';
  const isConnected = device.status === 'connected';
  return (
    <div className="device-row">
      <div className="device-icon" style={{ background: brandColor + '14', color: brandColor }}>{icon}</div>
      <div className="device-info">
        <div className="device-name-row">
          <span className="device-name">{device.name}</span>
          <StatusLabel status={device.status} />
        </div>
        <div className="device-meta">{device.brand} · {device.model}</div>
      </div>
      <button
        className={`device-action ${isConnected ? 'disconnect' : 'bind'}`}
        onClick={() => isConnected ? onDisconnect(device) : onBind(device)}
      >
        {isConnected ? '断开' : '绑定'}
      </button>
    </div>
  );
}

function HealthDetectionPage({ onGoBind }) {
  const [selectedMemberId, setSelectedMemberId] = useState('self');
  const [toast, setToast] = useState(null);
  const selectedMember = MEMBERS.find(m => m.id === selectedMemberId) || MEMBERS[0];

  const handleCardClick = (item) => {
    // Simulate: no bluetooth device bound for this measurement
    setToast(`请先绑定支持「${item.name}」的蓝牙设备`);
    setTimeout(() => {
      setToast(null);
      onGoBind();
    }, 800);
  };

  const totalCount = HEALTH_ITEMS.longTerm.length + HEALTH_ITEMS.instant.length;

  return (
    <div className="screen" data-screen-label="健康检测">
      <div className="nav-bar">
        <div className="nav-back">‹</div>
        <div className="nav-title">健康检测</div>
      </div>

      <div className="scroll health-scroll">
        <FamilySwitcher selectedMemberId={selectedMemberId} onSelect={setSelectedMemberId} />

        <div className="member-card">
          <div className="member-left">
            <div className="member-avatar-large">{selectedMember.avatar}</div>
            <div className="member-info">
              <div className="member-name-row">
                <span className="member-name">我（{selectedMember.name}）</span>
                <span className="member-tag">{selectedMember.relation}</span>
              </div>
              <div className="member-meta">{selectedMember.relation} · {selectedMember.age}岁 · {selectedMember.gender}</div>
            </div>
          </div>
          <div className="member-switch">⇄ 切换</div>
        </div>

        <div className="health-header">
          <div className="health-title-row">
            <span className="health-title">全部体征</span>
            <span className="health-count">{totalCount}项监测</span>
          </div>
        </div>

        <div className="health-group">
          <div className="health-group-title">
            <span className="health-group-icon" style={{ color: '#ff4d6d' }}>📡</span>
            <span>长程动态监测</span>
          </div>
          <div className="health-grid">
            {HEALTH_ITEMS.longTerm.map(item => (
              <div key={item.key} className="health-card" onClick={() => handleCardClick(item)}>
                <div className="health-card-icon" style={{ background: item.iconBg, color: item.iconColor }}>{item.icon}</div>
                <div className="health-card-name">{item.name}</div>
                <div className="health-card-hint" style={{ color: item.hintColor }}>{item.hint}</div>
                <div className="health-card-sub">{item.sub}</div>
              </div>
            ))}
          </div>
        </div>

        <div className="health-group">
          <div className="health-group-title">
            <span className="health-group-icon" style={{ color: '#2b7fff' }}>〰</span>
            <span>单次即时检测</span>
          </div>
          <div className="health-grid">
            {HEALTH_ITEMS.instant.map(item => (
              <div key={item.key} className="health-card" onClick={() => handleCardClick(item)}>
                {item.bluetooth && (
                  <div className="health-bluetooth">
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor">
                      <path d="M14.5 2l-8 8 5 5-5 5 8 8v-9l5 5v-14l-5 5v-8z" />
                    </svg>
                  </div>
                )}
                <div className="health-card-icon" style={{ background: item.iconBg, color: item.iconColor }}>{item.icon}</div>
                <div className="health-card-name">{item.name}</div>
                {item.value && (
                  <div className="health-card-value">
                    <span style={{ color: item.valueColor || '#1c2333' }}>{item.value}</span>
                    {item.unit && <span className="health-card-unit">{item.unit}</span>}
                  </div>
                )}
                <div className="health-card-time">
                  <span className="health-time-dot"></span>
                  {item.time}
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="health-bottom-spacer"></div>
      </div>

      <div className="health-footer">
        <div className="sync-btn" onClick={onGoBind}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
            <path d="M14.5 2l-8 8 5 5-5 5 8 8v-9l5 5v-14l-5 5v-8z" />
          </svg>
          同步设备数据
        </div>
      </div>

      {toast && (
        <div className="toast-mask">
          <div className="toast-panel">{toast}</div>
        </div>
      )}
    </div>
  );
}

function ManagePage({ devices, onBind, onDisconnect, onComplete, onBack }) {
  const [selectedMemberId, setSelectedMemberId] = useState('self');
  const selectedMember = MEMBERS.find(m => m.id === selectedMemberId) || MEMBERS[0];

  const grouped = useMemo(() => {
    const map = {};
    devices.forEach(d => {
      if (!map[d.brand]) map[d.brand] = [];
      map[d.brand].push(d);
    });
    return Object.entries(map);
  }, [devices]);

  const connectedCount = devices.filter(d => d.status === 'connected').length;

  return (
    <div className="screen" data-screen-label="设备绑定与管理">
      <div className="nav-bar">
        <div className="nav-back" onClick={onBack}>‹</div>
        <div className="nav-title">设备绑定与管理</div>
      </div>

      <div className="scroll">
        <FamilySwitcher selectedMemberId={selectedMemberId} onSelect={setSelectedMemberId} />

        <div className="member-card">
          <div className="member-left">
            <div className="member-avatar-large">{selectedMember.avatar}</div>
            <div className="member-info">
              <div className="member-name-row">
                <span className="member-name">我（{selectedMember.name}）</span>
                <span className="member-tag">{selectedMember.relation}</span>
              </div>
              <div className="member-meta">{selectedMember.relation} · {selectedMember.age}岁 · {selectedMember.gender}</div>
            </div>
          </div>
          <div className="member-switch">⇄ 切换</div>
        </div>

        <div className="section-header">
          <span className="section-title">绑定设备列表</span>
          <span className="section-count">{connectedCount}/{devices.length} 已连接</span>
        </div>

        {grouped.map(([brand, list]) => (
          <div key={brand}>
            <div className="brand-label">{brand}</div>
            <div className="device-list">
              {list.map(device => (
                <DeviceRow
                  key={device.id}
                  device={device}
                  onBind={onBind}
                  onDisconnect={onDisconnect}
                />
              ))}
            </div>
          </div>
        ))}

        <div className="bottom-btn" onClick={onComplete}>
          <span>✓</span> 完成
        </div>
      </div>
    </div>
  );
}

function BindPage({ device, onBack, onBindSubmit }) {
  const [sn, setSn] = useState('');
  const brandColor = BRAND_COLORS[device.brand.replace('医疗', '')] || COLORS.blue;
  const icon = ICONS[device.type] || '🔧';

  const handleScan = () => {
    setSn('SN' + Math.floor(Math.random() * 900000 + 100000));
  };

  return (
    <div className="screen" data-screen-label="输入设备 SN">
      <div className="nav-bar">
        <div className="nav-back" onClick={onBack}>‹</div>
        <div className="nav-title">绑定设备</div>
      </div>

      <div className="scroll">
        <div className="bind-card">
          <div className="bind-device-icon" style={{ background: brandColor + '14', color: brandColor }}>{icon}</div>
          <div className="bind-device-name">{device.name}</div>
          <div className="bind-device-meta">{device.brand} · {device.model}</div>

          <div className="input-label">设备序列号（SN）</div>
          <input
            className="sn-input"
            type="text"
            placeholder="请输入设备 SN 或扫码获取"
            value={sn}
            onChange={e => setSn(e.target.value)}
          />

          <div className="scan-btn" onClick={handleScan}>
            <span>📷</span> 扫码获取 SN
          </div>

          <div
            className={`bind-submit ${!sn.trim() ? 'disabled' : ''}`}
            onClick={() => sn.trim() && onBindSubmit(sn)}
          >
            确认绑定
          </div>

          <div className="bind-hint">
            SN 通常位于设备底部或包装盒上，输入后即可完成绑定。
          </div>
        </div>
      </div>
    </div>
  );
}

function PhoneScreen({ children }) {
  return (
    <div style={{
      width: 375, height: 812, borderRadius: 40, overflow: 'hidden',
      background: '#e7eaff', position: 'relative',
      boxShadow: '0 30px 70px rgba(0,0,0,0.15)',
      fontFamily: '-apple-system, "SF Pro Text", "PingFang SC", "Noto Sans SC", sans-serif',
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '14px 24px 8px', fontSize: 15, fontWeight: 600, color: '#1c2333',
      }}>
        <span>9:41</span>
        <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
          <svg width="17" height="12" viewBox="0 0 17 12">
            <rect x="0" y="7.5" width="3.2" height="4.5" rx="0.7" fill="#1c2333"/>
            <rect x="4.8" y="5" width="3.2" height="7" rx="0.7" fill="#1c2333"/>
            <rect x="9.6" y="2.5" width="3.2" height="9.5" rx="0.7" fill="#1c2333"/>
            <rect x="14.4" y="0" width="3.2" height="12" rx="0.7" fill="#1c2333"/>
          </svg>
          <svg width="15" height="12" viewBox="0 0 17 12">
            <path d="M8.5 3.2C10.8 3.2 12.9 4.1 14.4 5.6L15.5 4.5C13.7 2.7 11.2 1.5 8.5 1.5C5.8 1.5 3.3 2.7 1.5 4.5L2.6 5.6C4.1 4.1 6.2 3.2 8.5 3.2Z" fill="#1c2333"/>
            <path d="M8.5 6.8C9.9 6.8 11.1 7.3 12 8.2L13.1 7.1C11.8 5.9 10.2 5.1 8.5 5.1C6.8 5.1 5.2 5.9 3.9 7.1L5 8.2C5.9 7.3 7.1 6.8 8.5 6.8Z" fill="#1c2333"/>
            <circle cx="8.5" cy="10.5" r="1.5" fill="#1c2333"/>
          </svg>
          <svg width="25" height="12" viewBox="0 0 27 12">
            <rect x="0.5" y="0.5" width="23" height="12" rx="3.5" stroke="#1c2333" strokeOpacity="0.35" fill="none"/>
            <rect x="2" y="2" width="20" height="9" rx="2" fill="#1c2333"/>
          </svg>
        </div>
      </div>
      <div style={{ height: 'calc(100% - 34px)', display: 'flex', flexDirection: 'column' }}>{children}</div>
    </div>
  );
}

function App() {
  const [devices, setDevices] = useState(INITIAL_DEVICES);
  const [screen, setScreen] = useState('health');
  const [bindingDevice, setBindingDevice] = useState(null);

  const goHealth = () => { setScreen('health'); setBindingDevice(null); };
  const goManage = () => { setScreen('manage'); setBindingDevice(null); };
  const goBind = (device) => { setBindingDevice(device); setScreen('bind'); };

  const handleDisconnect = (device) => {
    setDevices(prev => prev.map(d => d.id === device.id ? { ...d, status: 'disconnected' } : d));
  };

  const handleBindSubmit = (sn) => {
    setDevices(prev => prev.map(d =>
      d.id === bindingDevice.id ? { ...d, status: 'connected' } : d
    ));
    setScreen('manage');
    setBindingDevice(null);
  };

  return (
    <PhoneScreen>
      {screen === 'health' && (
        <HealthDetectionPage onGoBind={goManage} />
      )}
      {screen === 'manage' && (
        <ManagePage
          devices={devices}
          onBind={goBind}
          onDisconnect={handleDisconnect}
          onComplete={goHealth}
          onBack={goHealth}
        />
      )}
      {screen === 'bind' && bindingDevice && (
        <BindPage
          device={bindingDevice}
          onBack={goManage}
          onBindSubmit={handleBindSubmit}
        />
      )}
    </PhoneScreen>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
