// Cube management subpage for manually configured GAN cube MAC addresses.
function CubeManager({ cubes, activeCubeId, onCubesChange, onActiveCubeChange, onBack }) {
  const [name, setName] = React.useState('');
  const [mac, setMac] = React.useState('');
  const [error, setError] = React.useState('');

  function persist(nextCubes, nextActiveId = activeCubeId) {
    onCubesChange(nextCubes);
    onActiveCubeChange(nextActiveId);
  }

  function addCube(e) {
    e.preventDefault();
    const normalizedMac = normalizeCubeMac(mac);
    if (!normalizedMac) {
      setError('Enter a MAC address as six hex bytes, for example AB:12:34:5D:34:12.');
      return;
    }
    if (cubes.some(c => c.mac === normalizedMac)) {
      setError('That MAC address is already saved.');
      return;
    }

    const cube = {
      id: `cube_${Date.now()}`,
      name: name.trim() || `GAN Cube ${cubes.length + 1}`,
      mac: normalizedMac,
    };
    persist([...cubes, cube], activeCubeId || cube.id);
    setName('');
    setMac('');
    setError('');
  }

  function deleteCube(id) {
    const next = cubes.filter(c => c.id !== id);
    const nextActiveId = activeCubeId === id ? (next[0]?.id || '') : activeCubeId;
    persist(next, nextActiveId);
  }

  function renameCube(id, nextName) {
    const next = cubes.map(c => c.id === id ? { ...c, name: nextName.trim() || c.name } : c);
    onCubesChange(next);
  }

  return (
    <div style={cubeStyles.page}>
      <div style={cubeStyles.header}>
        <div>
          <button type="button" style={cubeStyles.backBtn} onClick={onBack}>← Back to timer</button>
          <h1 style={cubeStyles.title}>Cube management</h1>
          <p style={cubeStyles.copy}>
            Save one or more GAN cube MAC addresses here. The selected cube's MAC is passed to
            the Bluetooth library after pairing so encrypted move data can be decoded.
          </p>
        </div>
      </div>

      <form onSubmit={addCube} style={cubeStyles.card}>
        <h2 style={cubeStyles.cardTitle}>Add cube</h2>
        <div style={cubeStyles.formGrid}>
          <label style={cubeStyles.field}>
            <span style={cubeStyles.label}>Name</span>
            <input
              style={cubeStyles.input}
              value={name}
              onChange={e => setName(e.target.value)}
              placeholder="GAN 12 UI"
            />
          </label>
          <label style={cubeStyles.field}>
            <span style={cubeStyles.label}>MAC address</span>
            <input
              style={cubeStyles.input}
              value={mac}
              onChange={e => setMac(e.target.value)}
              placeholder="AB:12:34:5D:34:12"
              autoCapitalize="characters"
            />
          </label>
          <button type="submit" style={cubeStyles.addBtn}>Add cube</button>
        </div>
        {error && <p style={cubeStyles.error}>{error}</p>}
      </form>

      <div style={cubeStyles.card}>
        <h2 style={cubeStyles.cardTitle}>Saved cubes</h2>
        {cubes.length === 0 ? (
          <p style={cubeStyles.empty}>No cubes saved yet. Add your cube's MAC address above.</p>
        ) : (
          <div style={cubeStyles.list}>
            {cubes.map(cube => (
              <div key={cube.id} style={cubeStyles.row}>
                <input
                  type="radio"
                  checked={cube.id === activeCubeId}
                  onChange={() => onActiveCubeChange(cube.id)}
                  style={cubeStyles.radio}
                  aria-label={`Use ${cube.name}`}
                />
                <div style={cubeStyles.rowMain}>
                  <input
                    style={cubeStyles.nameInput}
                    value={cube.name}
                    onChange={e => renameCube(cube.id, e.target.value)}
                    aria-label="Cube name"
                  />
                  <span style={cubeStyles.mac}>{cube.mac}</span>
                </div>
                {cube.id === activeCubeId && <span style={cubeStyles.activeBadge}>Active</span>}
                <button type="button" style={cubeStyles.deleteBtn} onClick={() => deleteCube(cube.id)}>Delete</button>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

const cubeStyles = {
  page: {
    minHeight: '100vh',
    background: 'oklch(10% 0.01 250)',
    color: 'oklch(85% 0.01 250)',
    fontFamily: "'Inter', sans-serif",
    padding: '28px 24px',
    maxWidth: '900px',
    margin: '0 auto',
  },
  header: { marginBottom: '20px' },
  backBtn: {
    background: 'none', border: 'none', color: 'oklch(55% 0.01 250)',
    cursor: 'pointer', fontSize: '13px', padding: 0, marginBottom: '14px',
    fontFamily: "'Inter', sans-serif",
  },
  title: { margin: 0, fontSize: '26px', color: 'oklch(90% 0.01 250)' },
  copy: {
    margin: '8px 0 0',
    color: 'oklch(55% 0.01 250)',
    fontSize: '14px',
    lineHeight: 1.5,
    maxWidth: '680px',
  },
  card: {
    background: 'oklch(14% 0.01 250)',
    border: '1px solid oklch(20% 0.01 250)',
    borderRadius: '10px',
    padding: '18px',
    marginBottom: '16px',
  },
  cardTitle: {
    margin: '0 0 14px',
    fontSize: '14px',
    letterSpacing: '0.06em',
    textTransform: 'uppercase',
    color: 'oklch(60% 0.01 250)',
  },
  formGrid: {
    display: 'grid',
    gridTemplateColumns: 'minmax(180px, 1fr) minmax(220px, 1fr) auto',
    gap: '12px',
    alignItems: 'end',
  },
  field: { display: 'flex', flexDirection: 'column', gap: '6px' },
  label: {
    fontSize: '11px',
    color: 'oklch(48% 0.01 250)',
    fontWeight: '600',
    letterSpacing: '0.08em',
    textTransform: 'uppercase',
  },
  input: {
    padding: '10px 12px',
    borderRadius: '8px',
    background: 'oklch(10% 0.01 250)',
    border: '1px solid oklch(24% 0.01 250)',
    color: 'oklch(90% 0.01 250)',
    fontSize: '14px',
    fontFamily: "'Inter', sans-serif",
    outline: 'none',
  },
  addBtn: {
    padding: '11px 16px',
    borderRadius: '8px',
    border: 'none',
    background: 'oklch(65% 0.18 165)',
    color: 'oklch(10% 0.01 250)',
    fontSize: '13px',
    fontWeight: '700',
    cursor: 'pointer',
    fontFamily: "'Inter', sans-serif",
  },
  error: { margin: '12px 0 0', color: 'oklch(65% 0.18 25)', fontSize: '13px' },
  empty: { color: 'oklch(42% 0.01 250)', margin: 0, fontSize: '13px' },
  list: { display: 'flex', flexDirection: 'column', gap: '8px' },
  row: {
    display: 'flex',
    alignItems: 'center',
    gap: '12px',
    padding: '12px',
    borderRadius: '8px',
    background: 'oklch(11% 0.01 250)',
    border: '1px solid oklch(20% 0.01 250)',
  },
  radio: { accentColor: 'oklch(65% 0.18 165)' },
  rowMain: { flex: 1, display: 'flex', flexDirection: 'column', gap: '4px', minWidth: 0 },
  nameInput: {
    background: 'transparent',
    border: 'none',
    color: 'oklch(82% 0.01 250)',
    fontSize: '14px',
    fontWeight: '600',
    fontFamily: "'Inter', sans-serif",
    outline: 'none',
    padding: 0,
  },
  mac: {
    color: 'oklch(48% 0.01 250)',
    fontSize: '12px',
    fontFamily: "'JetBrains Mono', monospace",
  },
  activeBadge: {
    color: 'oklch(65% 0.18 165)',
    background: 'oklch(18% 0.10 165)',
    borderRadius: '999px',
    padding: '3px 8px',
    fontSize: '11px',
    fontWeight: '700',
  },
  deleteBtn: {
    background: 'transparent',
    border: '1px solid oklch(25% 0.08 25)',
    color: 'oklch(60% 0.12 25)',
    borderRadius: '6px',
    padding: '6px 10px',
    cursor: 'pointer',
    fontSize: '12px',
    fontFamily: "'Inter', sans-serif",
  },
};

Object.assign(window, { CubeManager });
