/* First-load coach identity gate.
 *
 * Renders a non-dismissible modal that asks "Who are you?" the first time
 * either coach opens the app on this device. After that, the value lives
 * in localStorage and the gate is invisible.
 *
 * Wraps the rest of the app in render-children-when-known. Spec 3.7.
 */
(function () {
  const { useState, useEffect } = React;
  const { coach, Icons, tokens } = window.CC;

  function CoachGate({ children }) {
    const [me, setMe] = useState(coach.get());

    useEffect(() => {
      const onChange = (e) => setMe(e.detail);
      window.addEventListener("cc:coach-change", onChange);
      return () => window.removeEventListener("cc:coach-change", onChange);
    }, []);

    if (me) return children;
    return <CoachPicker onPick={(c) => coach.set(c)} />;
  }

  function CoachPicker({ onPick }) {
    return (
      <div className="cc-gate">
        <div className="cc-gate__card">
          <span
            className="cc-gate__brand"
            aria-hidden="true"
          />
          <h1 className="cc-gate__title">Who’s using this?</h1>
          <p className="cc-gate__sub">
            Tap your name. We’ll remember on this device.
          </p>
          <div className="cc-gate__row">
            <CoachTile coach="simon" onPick={onPick} />
            <CoachTile coach="perrie" onPick={onPick} />
          </div>
        </div>
      </div>
    );
  }

  function CoachTile({ coach: c, onPick }) {
    const colour = tokens.colors.coach[c];
    const label = window.CC.coach.label(c);
    return (
      <button
        type="button"
        className="cc-gate__tile"
        onClick={() => onPick(c)}
        style={{ "--tile-colour": colour }}
      >
        <span className="cc-gate__avatar">{label.charAt(0)}</span>
        <span className="cc-gate__name">{label}</span>
      </button>
    );
  }

  window.CC = window.CC || {};
  window.CC.CoachGate = CoachGate;
})();
