Code viewer for World: Color Matcher
//https://uiverse.io/G4b413l/smooth-fish-45 -> for bootstrap design of the cards
//https://www.w3schools.com/howto/howto_js_copy_clipboard.asp -> for copy and paste functionality of cards
//https://codepen.io/rakujira/pen/JjErROW -> color picker using iro.js


const openaiURL = "https://api.cohere.ai/v1/generate";         
  
const themodel = "command";       
    



var apikey = "GnB73I8Xq3YFTmLHrorKsYJClCT9t03ElzgHGTtm";
var theprompt = "";



  $('body').css( "margin", "20px" );
  $('body').css( "padding", "20px" );


 
document.write ( `
<head>
<div class="container center-content">
<h1>Find Matching Colours</h1>
</div>
<script src="https://cdn.jsdelivr.net/npm/@jaames/iro@5"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<style>
@import url('https://fonts.googleapis.com/css2?family=Lilita+One&family=Roboto&display=swap');
.center-content {
    font-family: "Roboto";
    display: flex;
    justify-content: center;
    align-items: center;
    color:	#5A5A5A;
    }
.btn-text-center {
    text-align: center;
  }
  
  
.card {
  position: relative;
  width: 11.875em;
  height: 16.5em;
  box-shadow: 0px 1px 13px rgba(0,0,0,0.1);
  cursor: pointer;
  transition: all 120ms;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  padding: 0.5em;
  padding-bottom: 3.4em;
}

.card .title {
  font-family: "Roboto";
  font-size: 0.9em;
  position: absolute;
  left: 0.625em;
  bottom: 1.875em;
  font-weight: 400;
  color: #000;
}

.card:hover::after {
  bottom: 0;
  opacity: 1;
}

.card:active {
  transform: scale(0.98);
}

.card:active::after {
  content: "Copied";
  height: 3.125em;
}

.text {
  max-width: 55px;
}

.image {
  width: 100%;
  height: 100%;
  display: grid;
  place-items: center;
  background-color: #ffffff; /* Set a default color */
}

.values{
    
    font-weight: bold;
}
}

</style>

<pre>

</pre>
<div class="container center-content">
<h3> Enter API key </h3>
</div>

<div class = "container center-content">
<div id=enterkey>
	<input    style='width:25vw;'    maxlength='2000'   NAME="apikey"    id="apikey"       VALUE='' >  
	<button onclick="setkey();" class="btn btn-outline-primary btn-sm waves-effect text-center">
      <i class="fas fa-key" aria-hidden="true"></i> Set API key
</div>
</div>
<pre>
<div class="container">
   <div class="row justify-content-center">
    <div class="col">
      <button id= "compbtn" type="button" class="btn btn-outline-primary btn-sm waves-effect">
        <i class="fas fa-sun" aria-hidden="true"></i>Complementary
      </button>
    </div>
    <div class="col">
      <button id = "analagousbtn" type="button" class="btn btn-outline-primary btn-sm waves-effect">
        <i class="fas fa-sun" aria-hidden="true"></i>Analogous
      </button>
    </div>
    <div class="col">
      <button id = "tetradicbtn" type="button" class="btn btn-outline-primary btn-sm waves-effect">
        <i class="fas fa-sun" aria-hidden="true"></i>Tetradic
      </button>
    </div>
    <div class="col">
      <button id = "triadicbtn" type="button" class="btn btn-outline-primary btn-sm waves-effect text-center">
        <i class="fas fa-sun" aria-hidden="true"></i>Triadic
      </button>
    </div>
    <div class="col">
      <button id = "squarebtn" type="button" class="btn btn-outline-primary btn-sm waves-effect">
        <i class="fas fa-sun pr-2" aria-hidden="true"></i>Square
      </button>
    </div>
  </div>
</div>


</pre>
<div class="container center-content">
  <div class="row">
    <div class="col-xl-6">
      <div style="background-color: white; border: 1px solid black; margin: 20px; padding: 20px;">
        <div class="ColorPicker" id="boxPicker">
          <div id="values"></div>
        </div>
        <br>
        <button onclick="previewcolour();" class="ab-normbutton">Preview Colour</button>
      </div>
    </div>
    <div class="col-xl-6">
      <div style="background-color: white; border: 1px solid black; margin: 30px; padding: 20px;">
        <h3>Enter a Hexcode</h3>
        <div class="input-group">
          <input style="width:100%;" class="form-control" placeholder="Enter Hexcode" id="me">
          <button onclick="sendchat();" class="btn btn-outline-primary btn-sm waves-effect">Send</button>
        </div>
      </div>
    </div>
  </div>
</div>


<div class="container">
  <div class="row justify-content-center mt-4">
    <div class="col-8">
      <div class="bg-light border p-4">
      <div id="suggestions"></div>
        <div id="them"></div>
      </div>
    </div>
  </div>
</div>


  <script>
    var boxPicker = new iro.ColorPicker("#boxPicker", {
      width: 250,
      color: "rgb(255, 0, 0)",
      borderWidth: 1,
      borderColor: "#fff",
      layout: [
        {
          component: iro.ui.Box,
        },
        {
          component: iro.ui.Slider,
          options: {
            id: 'hue-slider',
            sliderType: 'hue'
          }
        }
      ]
    });
    
    
    var values = document.getElementById("values");
    boxPicker.on(["color:init", "color:change"], function(color){
    values.innerHTML = [
    "hex: " + color.hexString,
  ].join("<br>");
});


  </script>
<pre>

</pre>

` );






function setkey()          
{
	apikey =  jQuery("input#apikey").val();
	apikey = apikey.trim();
	$("#enterkey").html ( "<b> API key has been set. </b>" );
}

document.addEventListener('DOMContentLoaded', (event) => {
  const inputElement = document.getElementById('me');

  if (inputElement) {
    inputElement.addEventListener('keydown', function(event) {
      if (event.keyCode === 13) {
        sendchat();
      }
    });
  }
});



//-------------------------------------------------------------Buttons
var buttonType = "";

document.addEventListener('DOMContentLoaded', (event) => {
  const compbtn = document.getElementById('compbtn');

  if (compbtn) {
    compbtn.addEventListener('click', function(event) {
      console.log('Complementary button clicked!');
      buttonType = "Complementary";
    });
  }
});

document.addEventListener('DOMContentLoaded', (event) => {
  const triadicbtn = document.getElementById('triadicbtn');

  if (triadicbtn) {
    triadicbtn.addEventListener('click', function(event) {
      console.log('Triadic button clicked!');
      buttonType = "Triadic";
    });
  }
});


document.addEventListener('DOMContentLoaded', (event) => {
  const tetradicbtn = document.getElementById('tetradicbtn');

  if (tetradicbtn) {
    tetradicbtn.addEventListener('click', function(event) {
      console.log('Tetradic button clicked!');
      buttonType = "Tetradic";
    });
  }
});

document.addEventListener('DOMContentLoaded', (event) => {
  const analagousbtn = document.getElementById('analagousbtn');

  if (analagousbtn) {
    analagousbtn.addEventListener('click', function(event) {
      console.log('Analogous button clicked!');
      buttonType = "Analogous";
    });
  }
});

document.addEventListener('DOMContentLoaded', (event) => {
  const squarebtn = document.getElementById('squarebtn');

  if (squarebtn) {
    squarebtn.addEventListener('click', function(event) {
      buttonType = "Square";
      console.log('Square button clicked!');
    });
  }
});




// --- Send my line of text ----------------------------------------------------------------
function sendchat() {
  const me = document.getElementById('me').value;
  if(me.length == 7 && me.startsWith('#')){
  const options = {
    method: 'POST',
    headers: {
      accept: 'application/json',
      'content-type': 'application/json',
      authorization: 'Bearer ' + apikey
    },
    body: JSON.stringify({
      truncate: 'END',
      return_likelihoods: 'NONE',
      prompt: "can you generate hexcodes that are " + buttonType + " to "+ me
    })
  };


// MH edit
console.log ( "MH can you generate hexcodes that are " + buttonType + " to "+ me  );


  fetch('https://api.cohere.ai/v1/generate', options)
    .then(response => response.json())
    .then(response => {
        console.log(response)
        const text = response.generations[0].text; 
        const repliesDiv = document.getElementById('them');

        if (text) {
              repliesDiv.innerHTML = ''; 

            const hexCodes = extractHexCodes(text, me);
            hexCodes.forEach(hex => {
                
                const card = document.createElement('div');
                card.classList.add('card'); 

               
                const imageDiv = document.createElement('div');
                imageDiv.classList.add('image');
                imageDiv.style.backgroundColor = hex;
                card.appendChild(imageDiv);

            
                const paragraph = document.createElement('p');
                paragraph.textContent = hex;
                paragraph.id = 'hexCodeText';
                card.appendChild(paragraph);
                
                card.addEventListener('click', function() {
    const hexCodeText = this.querySelector('#hexCodeText').textContent;

    navigator.clipboard.writeText(hexCodeText)
        .then(() => {
            alert('Hex code copied to clipboard: ' + hexCodeText);
        })
        .catch(err => {
            console.error('Error copying hex code: ', err);
        });
});

                repliesDiv.appendChild(card);
            });
        } else {
            repliesDiv.textContent = 'Oops! Unable to fetch a valid response.';
        }
    })
    .catch(err => console.error(err));
}}
function extractHexCodes(text, inputHex) {
    const hexRegex = /#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})\b/g;
    const hexCodes = text.match(hexRegex) || [];
 
    const uniqueHexCodes = new Set();

   
    hexCodes.forEach(hex => {
        const lowerHex = hex.toLowerCase();
        if (lowerHex !== inputHex.toLowerCase()) {
            uniqueHexCodes.add(lowerHex);
        }
    });

  
    return Array.from(uniqueHexCodes);
}

function previewcolour() {
  const hexCode = document.getElementById('values').innerText.split(' ')[1]; 

  if (hexCode) {
    const repliesDiv = document.getElementById('them');
    repliesDiv.innerHTML = '';

    const card = document.createElement('div');
    card.classList.add('card');

 
    const imageDiv = document.createElement('div');
    imageDiv.classList.add('image');
    imageDiv.style.backgroundColor = hexCode; 
    card.appendChild(imageDiv);

  
    const paragraph = document.createElement('p');
    paragraph.textContent = hexCode;
    paragraph.id = 'hexCodeText';
    card.appendChild(paragraph);
    
    card.addEventListener('click', function() {
    const hexCodeText = this.querySelector('#hexCodeText').textContent;

    navigator.clipboard.writeText(hexCodeText)
        .then(() => {
            alert('Hex code copied to clipboard: ' + hexCodeText);
        })
        .catch(err => {
            console.error('Error copying hex code: ', err);
        });
});


    repliesDiv.innerHTML = ''; 
    repliesDiv.appendChild(card);
  } else {
    console.log('No hex code found in the values element.');
  }
}

const card = document.createElement('div');
card.addEventListener('click', function() {
    const hexCodeText = this.querySelector('#hexCodeText').textContent;

    navigator.clipboard.writeText(hexCodeText)
        .then(() => {
            alert('Hex code copied to clipboard: ' + hexCodeText);
        })
        .catch(err => {
            console.error('Error copying hex code: ', err);
        });
});