/* Capture (home) — three big buttons + recent activity peek.
 *
 * The screen 95% of interactions hit. Spec section 4.2.
 */
(function () {
  const { useState, useEffect } = React;
  const {
    Card,
    Avatar,
    Pill,
    Icons,
    showToast,
    CaptureMember,
    CaptureClass,
    CaptureNote,
    fb,
    coach,
    tokens,
    time,
    members,
  } = window.CC;

  function Capture() {
    const [openFlow, setOpenFlow] = useState(null);
    const [recent, setRecent] = useState([]);
    const [showPending, setShowPending] = useState(true);
    const [memberMeta, setMemberMeta] = useState(window.CC.members.meta());

    useEffect(() => {
      const off = fb.listen("entries", (val) => {
        const arr = val
          ? Object.values(val).filter((e) => !e.deleted)
          : [];
        arr.sort((a, b) => b.created_at - a.created_at);
        setRecent(arr.slice(0, 3));
      });
      return off;
    }, []);
    useEffect(
      () => window.CC.members.subscribe((_, m) => setMemberMeta(m)),
      []
    );
    useEffect(() => {
      const onShortcut = () => setOpenFlow("note");
      window.addEventListener("cc:shortcut-new", onShortcut);
      return () => window.removeEventListener("cc:shortcut-new", onShortcut);
    }, []);

    const me = coach.get() || "simon";
    const meLabel = coach.label(me);
    const showSetupBanner =
      showPending && memberMeta.source === "placeholder";

    return (
      <>
        <div className="cc-capture">
          <header className="cc-capture__top">
            <span className="cc-capture__me">{me}</span>
            <button
              type="button"
              aria-label="Notifications"
              className="cc-capture__bell"
            >
              {Icons.bell(20)}
            </button>
          </header>

          {showSetupBanner && (
            <div style={{ marginBottom: 16 }}>
              <window.CC.Banner
                tone="info"
                message="Member list is using placeholders. Connect your sheet to load the real members."
                action={{
                  label: "Open Settings",
                  onClick: () => (window.location.hash = "/settings"),
                }}
                onDismiss={() => setShowPending(false)}
              />
            </div>
          )}

          <div className="cc-capture__buttons">
            <CaptureButton
              icon={Icons.member(28)}
              label="Member update"
              hint={`Log a change for one of ${meLabel}'s members`}
              onClick={() => setOpenFlow("member")}
            />
            <CaptureButton
              icon={Icons.class(28)}
              label="Class summary"
              hint="Debrief the class you just ran"
              onClick={() => setOpenFlow("class")}
            />
            <CaptureButton
              icon={Icons.note(28)}
              label="Anything else"
              hint="Decisions, ideas, FYIs, wins"
              onClick={() => setOpenFlow("note")}
            />
          </div>

          <RecentPeek entries={recent} />
        </div>

        <CaptureMember
          open={openFlow === "member"}
          onClose={() => setOpenFlow(null)}
          onSaved={() => showToast("Saved.")}
        />
        <CaptureClass
          open={openFlow === "class"}
          onClose={() => setOpenFlow(null)}
          onSaved={() => showToast("Class summary saved.")}
        />
        <CaptureNote
          open={openFlow === "note"}
          onClose={() => setOpenFlow(null)}
          onSaved={() => showToast("Saved.")}
        />
      </>
    );
  }

  function CaptureButton({ variant, icon, label, hint, onClick }) {
    return (
      <button
        type="button"
        onClick={onClick}
        className={`cc-capture-btn cc-capture-btn--${variant || "neutral"}`}
      >
        <span className="cc-capture-btn__icon">{icon}</span>
        <span className="cc-capture-btn__text">
          <span className="cc-capture-btn__label">{label}</span>
          <span className="cc-capture-btn__hint">{hint}</span>
        </span>
        <span className="cc-capture-btn__chev">{Icons.chevronRight(18)}</span>
      </button>
    );
  }

  function RecentPeek({ entries }) {
    if (!entries.length) {
      return (
        <div className="cc-recent-peek cc-recent-peek--empty">
          Nothing logged yet today. The capture buttons above are where
          everything starts.
        </div>
      );
    }
    return (
      <div className="cc-recent-peek">
        <div className="cc-recent-peek__head">
          <span>Recent activity</span>
          <a href="#/hub/recent" className="cc-recent-peek__more">
            View all →
          </a>
        </div>
        <ul className="cc-recent-peek__list">
          {entries.map((e) => (
            <li key={e.id}>
              <Avatar
                coach={e.coach}
                size={24}
                label={window.CC.coach.label(e.coach)}
              />
              <span className="cc-recent-peek__type">
                {e.type === "member" ? "Member" : e.type === "class" ? "Class" : "Note"}
              </span>
              <span className="cc-recent-peek__body">{e.body}</span>
              <span className="cc-recent-peek__time">
                {time.relative(e.created_at)}
              </span>
            </li>
          ))}
        </ul>
      </div>
    );
  }

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