/* global React, window */
const { NOTES, Sketch, FieldLine, TAGS, LGStore, useLGStore, IcoX, IcoChevron } = window;

/* =============================================================
 * FOLDER TAB — a single tag rendered as a manila folder tab.
 * Click to pull the folder forward (toggle the tag).
 * Active state: tab lifts higher + ink stamp on top edge.
 * ============================================================= */
function FolderTab({ tag, count, active, onClick }) {
  return (
    <button
      type="button"
      className={"folder-tab" + (active ? " folder-tab--active" : "")}
      onClick={onClick}
      title={tag.label + " · " + count + (count === 1 ? " entry" : " entries")}
      style={{ '--leather': tag.leather }}
    >
      <span className="folder-tab__swatch" aria-hidden="true" />
      <span className="folder-tab__label">{tag.label}</span>
      <span className="folder-tab__count">{count.toString().padStart(2, '0')}</span>
    </button>
  );
}

/* =============================================================
 * FOLDER RACK — horizontal row of folder tabs.
 * Multi-select: activeTags is an array. Click toggles a tag in/out.
 * The "All Notes" master tab (dark-stamped) clears the selection.
 * ============================================================= */
function FolderRack({ tags, counts, activeTags, toggleTag, clearTags }) {
  const isAll = !activeTags || activeTags.length === 0;
  return (
    <div className="folder-rack">
      <button
        type="button"
        className={"folder-tab folder-tab--all" + (isAll ? " folder-tab--active" : "")}
        onClick={clearTags}
      >
        <span className="folder-tab__label">All Notes</span>
        <span className="folder-tab__count">{counts.__total}</span>
      </button>
      {tags.map(tag => (
        <FolderTab
          key={tag.id}
          tag={tag}
          count={counts[tag.id] || 0}
          active={activeTags.includes(tag.id)}
          onClick={() => toggleTag(tag.id)}
        />
      ))}
    </div>
  );
}

/* =============================================================
 * NOTES INDEX — main archive page
 * ============================================================= */
function NotesIndex({ go }) {
  useLGStore();
  const [q, setQ] = React.useState("");
  // Multi-select: empty array = "All Notes". Click a book to toggle.
  const [activeTags, setActiveTags] = React.useState([]);
  const toggleTag = (id) => {
    setActiveTags(prev => prev.includes(id) ? prev.filter(t => t !== id) : [...prev, id]);
  };
  const clearTags = () => setActiveTags([]);

  // Combined corpus: seeded NOTES + saved field-desk entries
  const all = React.useMemo(() => {
    const saved = LGStore.list("entries").map((e, i, arr) => ({
      ...e,
      no: "№ " + String(arr.length - i).padStart(3, "0"),
      category: e.category || "Field Note",
      excerpt: e.preview || (e.body ? e.body.slice(0, 140) + "…" : ""),
      tags: e.tags || [],
      _saved: true
    }));
    return [...saved, ...NOTES];
  }, [LGStore.list("entries").length]);

  // counts per tag, plus total
  const counts = React.useMemo(() => {
    const c = { __total: all.length };
    TAGS.forEach(t => { c[t.id] = 0; });
    all.forEach(n => (n.tags || []).forEach(id => { if (c[id] != null) c[id]++; }));
    return c;
  }, [all]);

  const filtered = all.filter(n => {
    // Multi-select: a note matches if ANY of its tags is in the active set.
    // No active tags = show everything (the "All Notes" state).
    const matchTag = activeTags.length === 0 || (n.tags || []).some(t => activeTags.includes(t));
    const hay = (n.title + " " + (n.location || "") + " " + (n.excerpt || "") + " " + (n.body || "") + " " + (n.tags || []).join(" ")).toLowerCase();
    const matchQ = !q || hay.includes(q.toLowerCase());
    return matchTag && matchQ;
  });

  const activeTagObjs = activeTags.map(id => TAGS.find(t => t.id === id)).filter(Boolean);

  return (
    <main className="archive">
      {/* HEAD */}
      <section className="container archive__head">
        <div className="archive__rule">
          <span className="eyebrow">The Archive</span>
          <span className="archive__rule-line" />
          <span className="eyebrow">{filtered.length} of {all.length}</span>
        </div>
        <h1 className="display archive__title">Goat<br/>Notes</h1>
        <p className="serif archive__lede">
          Filed dispatches from places that take some getting to. Pull a folder
          forward to sort by what's filed inside.
        </p>
      </section>

      {/* RACK */}
      <section className="container archive__rack">
        <div className="archive__rack-head">
          <span className="eyebrow">Sort by tag</span>
          <span className="serif archive__rack-hint">Pull a folder forward · or pick "All Notes"</span>
        </div>
        <FolderRack
          tags={TAGS}
          counts={counts}
          activeTags={activeTags}
          toggleTag={toggleTag}
          clearTags={clearTags}
        />
        {activeTagObjs.length > 0 && (
          <div className="archive__active-tag">
            <span className="eyebrow">Reading from</span>
            <div className="archive__active-chips">
              {activeTagObjs.map(t => (
                <button
                  key={t.id}
                  type="button"
                  className="archive__active-chip"
                  style={{ '--leather': t.leather }}
                  onClick={() => toggleTag(t.id)}
                  title={"Remove " + t.label}
                >
                  <span>{t.label}</span>
                  <IcoX size={11} />
                </button>
              ))}
            </div>
            <button className="archive__active-clear" onClick={clearTags}>
              <IcoX size={12} /> <span>back to all</span>
            </button>
          </div>
        )}
      </section>

      {/* SEARCH */}
      <section className="container archive__search">
        <div className="searchbar">
          <span className="searchbar__lead">Search →</span>
          <input
            className="searchbar__in"
            value={q}
            onChange={(e) => setQ(e.target.value)}
            placeholder="storm · campfire · Pinto Canyon · father · third log"
          />
          {q && (
            <button className="searchbar__clear" onClick={() => setQ("")} title="Clear">
              <IcoX size={14} />
            </button>
          )}
        </div>
      </section>

      {/* LIST */}
      <section className="container archive__list">
        {filtered.map((n, i) => (
          <article key={n.id || i} onClick={() => go("note:" + n.id)} className={"entry" + (n._saved ? " entry--saved" : "")}>
            <div className="entry__no">
              <div className="display entry__num">{(n.no || "").replace("№ ", "") || "—"}</div>
              <div className="eyebrow entry__date">{(n.date || "").split(",")[0]}</div>
            </div>
            <div className="entry__body">
              <div className="eyebrow entry__cat">{n.category}</div>
              <h3 className="display entry__title">{n.title || "Untitled"}</h3>
              <p className="serif entry__excerpt">{n.excerpt}</p>
              {n.tags && n.tags.length > 0 && (
                <div className="entry__tags">
                  {n.tags.map(tid => {
                    const t = TAGS.find(x => x.id === tid);
                    if (!t) return null;
                    return (
                      <span
                        key={tid}
                        className={"tagchip tagchip--read" + (activeTags.includes(tid) ? " tagchip--on" : "")}
                        style={{ '--leather': t.leather, cursor: 'pointer' }}
                        onClick={(e) => { e.stopPropagation(); toggleTag(tid); }}
                      >
                        {t.label}
                      </span>
                    );
                  })}
                </div>
              )}
            </div>
            <div className="entry__meta">
              {n.location && <FieldLine label="Loc." value={n.location} />}
              {n.coords && <FieldLine label="Coord." value={n.coords} />}
              {n.weather && <FieldLine label="Wx." value={n.weather} />}
              {typeof n.wordCount === "number" && (
                <FieldLine label="Words" value={`${n.wordCount.toLocaleString()} words`} />
              )}
            </div>
            <div className="entry__sketch">
              <Sketch kind={["mountains","truck","fire","map","kettle","compass","sunset","stars","agave","ocotillo","storm","whiskey"][i % 12]} height={90} />
            </div>
          </article>
        ))}
        {filtered.length === 0 && (
          <div className="archive__empty">
            <span className="hand">Nothing filed under that yet. Try a different word.</span>
          </div>
        )}
      </section>
    </main>
  );
}

window.NotesIndex = NotesIndex;
