import shortlinkLogo from './assets/trx-shortlink-orange.png'
import './App.css'

const Home = () => {
    return (
        <>
      <header>
      <div className="nav">
        <nav id="main-nav">
        <ul id="centerlist">
          <li id="home"> <a draggable="false" href="/home">Home</a> </li>
          
          
        </ul>
        <ul id="rightlist">
          <li id="login"> <a draggable="false" href='/login'>Login</a></li>
        </ul>
      </nav>
      </div>
      </header>
      <div id="logoname">
        <a href="/home" >
          <img src={shortlinkLogo} draggable="false" className="logo" alt="trx shortlink logo" />
        </a>
        <h1>trx shortlink</h1>
      </div>
      <div className="card">
        <input className="input" id="oriurl"></input>
        <button id="button_short" onClick={() => shortenLink((document.getElementById("oriurl") as HTMLInputElement).value)
        }>
          Shorten link!
        </button>
      </div>
    </>
    );
};

export default Home;

async function shortenLink(url: string) {
          const inputi = (document.getElementById("oriurl") as HTMLInputElement).value;
          if (inputi == "") {
            alert("The url cannot be empty!")
          } else if(!(inputi.startsWith("https://") || inputi.startsWith("http://"))) {
            alert("Please provide a valid url!")
          } else {
          const res = await fetch("http://localhost:3000/api/shorten", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ original_url: url }),
          });
          const data = await res.json();
          console.log(data.short_url);
          (document.getElementById("oriurl") as HTMLInputElement).value = ""
          location.href = "/link/" + data.id;
          return data.id;
          }
        }


