       when g then (b - r) / diff + 2
       when b then (r - g) / diff + 4
 
+bg2rgb = (bg) ->
+  [ _, r, g, b ] = bg.split /(?:rgb\()|(?:, )|\)/
+  '#' + (hex(parseInt c) for c in [r, g, b]).join ''
+
+# use of golden ratio inspired by
+# //martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/
+# this is a bit more complicated than that case, since rather than generating
+# all colors at once, we're reacting to user color edits as well
 pickNewColor = (colors) ->
   hues = (rgb2hue color for color in colors)
     .sort (a, b) ->
       a - b
-  [ begin, offset ] = (hues.map (v, i, arr) ->
-      [i, (arr[i + 1] ? arr[0] + 1) - v]
+  [ begin, offset ] = (hues.map (v, i) ->
+      [i, (hues[i + 1] ? hues[0] + 1) - v]
     .sort ([ai, av], [bi, bv]) ->
-      bv - av)[0]                      # backwards so the maximum will be first
-  offset = 1 unless offset
+      bv - av)[0]                 # sort backwards so the maximum will be first
+  offset = 1 unless offset        # correction for the single-hue case
   hue2rgb hues[begin] + PHI * offset
 
-
+# regular gui stuff
 create = (url, x, y) ->
   chrome.windows.create
     url: url

#    ({tabs: [ { windowId } ] }) ->
#      chrome.windows.update windowId, drawAttention: yes

document.querySelector '#add'
  .addEventListener 'click', ({screenX, screenY}) ->
    storage.get (items) ->
      create "edit.html?color=#{encodeURIComponent pickNewColor (
          color for {color} in items)}", screenX, screenY

update = ->
  storage.get (items) ->
    hats = document.querySelector '#hats'
    # start with empty div
    while hats.firstChild

V = 0.95
P = V * (1 - S)

hex = (c) ->
  h = c.toString 16
  "#{if h.length < 2 then '0' else ''}#{h}"

# generated colors will have constant saturation and value
hue2rgb = (hue) ->
  i = Math.floor hue * 6
  f = hue * 6 - i
  q = V * (1 - f * S)
  t = V * (1 - (1 - f) * S)
  [r, g, b] = switch i % 6
    when 0 then [ V, t, P ]
    when 1 then [ q, V, P ]
