import {Link, Outlet, useLoaderData} from "react-router-dom";
import {getContacts} from "../contacts.js";

export async function loader() {
  const contacts = await getContacts();
  return {contacts};
}

export default function root() {
  const contacts = useLoaderData();
  return (
    <>
      <div id="sidebar">
        <h1>React Router contacts</h1>
        <div>
          <form id="search-form" role="search">
            <input id="q" aria-label="Search contacts" placeholder="search" name="q" type="search"/>
            <div id="search-spinner" aria-hidden hidden={true}/>
            <div className="sr-only" aria-live="polite"></div>
          </form>
          <form method="post">
            <button type="submit">New</button>
          </form>
        </div>
        <nav>
          {contacts.length ? (
            <ul>
              {contacts.map((contact) => (
                <li key={contact.id}>
                  <Link to={`contacts/${contact.id}`}>
                    {contact.first || contact.last ? (
                      <>
                        {contact.first} {contact.last}
                      </>
                    ) : (
                      <i>No name</i>
                    )}{" "}
                    {contact.favorite && <span>*</span>}
                  </Link>
                </li>
              ))
              }
            </ul>
          ) : (
            <p><i>No contacts</i></p>
          )}
        </nav>
      </div>
      <div id="detail">
        <Outlet/>
      </div>
    </>
  )
    ;
};