// entries are HTML (e.g. links)
// requires JQuery for click-outside-to-close trick
// Note: Make sure containing elements have overflow: visible,
// otherwise pop-up can get cut off
sclass HPopDownButton {
  S labelHTML;
  S buttonHTML = htmlEncode2(unicode_smallDownPointingTriangle());
  new LS entries;
  S id = "dropdown-" + aGlobalID(), outerID = "outer-" + id;
  S style = "position: relative; display: inline-block; cursor: context-menu";
  S menuStyle = "";
  
  *() {}
  *(S *labelHTML, LS entries) { addAll(this.entries, entries); }
  
  S onclick() {
    ret replaceDollarVars([[
      var x = document.getElementById($id);
      x.style.display = window.getComputedStyle(x).display === "none" ? "block" : "none";
      console.log("popup " + id + " display: " + x.style.display);
    ]], id := jsQuote(id));
  }
  
  S html() {
    ret hstyle(replaceDollarVars([[
      #$id ul {
        list-style-type: none;
        margin: 0;
        padding: 0;
        width: 200px;
        background-color: #f1f1f1;
      }
      
      #$id {
        position: absolute;
        display:none;
        background-color: #f9f9f9;
        width:auto;
        height:200px;
        overflow: auto;
       
        min-width: 160px;
        box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
        
        z-index: 99;
      }
      
      #$id li a {
        text-decoration: none;
        color: #000;
      }
  
      #$id li {    
        display: block;
        border-bottom: 1px solid #555;
        padding: 8px 16px;
        color: #000;
      }
      
      #$id li:hover, #$id li:hover > a {
        background-color: #3399ff;
        color: white;
      }
    ]], +id))
    + hdiv(
          buttonHTMLWithOnClick()
        + hdiv(ul(entries), +id, style := menuStyle),
      +style, id := outerID)
      + hscript(replaceDollarVars([[
        if (typeof $ !== 'undefined')
          $('body').click(function(e) {
            if (!$(e.target).closest('#$outerID').length) {
              $("#$id").hide();
            }
          });
      ]], +id, +outerID));
  }
  
  swappable S buttonHTMLWithOnClick() {
    ret span(joinNemptiesWithSpace(labelHTML, buttonHTML), onclick := onclick());
  }
}