/* Pressing Identification Guide — a practical, readable guide to working out
   which pressing of a record you actually own. Linked from the footer, the
   add-record flow, and the album collector's corner. */

const { useState: usePgState } = React;

/* Standalone matrix / runout identifier. Unlike the one in the add-record flow,
   this isn't tied to a chosen album — the user types the artist and title plus
   the runout, and we show the matching pressings with current Discogs prices.
   Reuses the same /api/identify endpoint and the add-matrix-* styles. */
function MatrixIdentifier() {
  const [artist, setArtist] = usePgState("");
  const [title, setTitle] = usePgState("");
  const [runout, setRunout] = usePgState("");
  const [busy, setBusy] = usePgState(false);
  const [note, setNote] = usePgState("");
  const [results, setResults] = usePgState([]);

  const canRun = artist.trim() && title.trim() && runout.trim() && !busy;

  async function run() {
    if (!canRun) return;
    setBusy(true);
    setNote("");
    setResults([]);
    try {
      const q = encodeURIComponent(artist.trim() + " " + title.trim());
      const matrix = encodeURIComponent(runout.trim());
      const r = await fetch(`/api/identify?q=${q}&matrix=${matrix}`);
      const j = await r.json();
      const cands = j.candidates || [];
      setResults(cands);
      if (!cands.length) {
        if (j.checked > 0) {
          setNote(`That runout doesn't match any catalogued pressing of "${title.trim()}". Double-check you've read it correctly, character for character, and that it's from this record.`);
        } else {
          setNote(j.note || "No match found. Check the artist and title spelling and your runout transcription, then try again.");
        }
      } else {
        setNote(j.note || "");
      }
    } catch (e) {
      setNote("Couldn't reach the identifier just now. Please try again in a moment.");
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="add-matrix pg-identifier">
      <div className="add-matrix-panel">
        <p className="add-matrix-hint">
          Enter the artist and album, then type the runout exactly as etched, and we'll find the matching
          pressing on Discogs along with current market prices.
        </p>
        <div className="pg-identifier-fields">
          <input
            className="add-matrix-input"
            type="text"
            placeholder="Artist (e.g. Pink Floyd)"
            value={artist}
            onChange={(e) => setArtist(e.target.value)}
            onKeyDown={(e) => { if (e.key === "Enter") run(); }}
          />
          <input
            className="add-matrix-input"
            type="text"
            placeholder="Album (e.g. The Dark Side of the Moon)"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            onKeyDown={(e) => { if (e.key === "Enter") run(); }}
          />
        </div>
        <div className="add-matrix-row">
          <input
            className="add-matrix-input"
            type="text"
            placeholder="Runout / matrix (e.g. SHVL 804 A-2)"
            value={runout}
            onChange={(e) => setRunout(e.target.value)}
            onKeyDown={(e) => { if (e.key === "Enter") run(); }}
          />
          <button className="add-matrix-go" disabled={!canRun} onClick={run}>
            {busy ? "Searching…" : "Identify"}
          </button>
        </div>
        {busy && (
          <div className="add-matrix-loading">
            <span className="add-matrix-spinner" aria-hidden="true" />
            <span className="add-matrix-loading-text">
              Searching for matching pressings… this can take a few seconds.
            </span>
          </div>
        )}
        {!busy && note && <div className="add-matrix-note">{note}</div>}
        {results.length > 0 && (
          <div className="add-matrix-results">
            {results.map((c) => (
              <div key={c.id} className="add-matrix-res pg-matrix-res">
                {c.thumb ? <img className="add-matrix-thumb" src={c.thumb} alt="" /> : <span className="add-matrix-thumb add-matrix-thumb-blank" />}
                <span className="add-matrix-res-main">
                  <span className="add-matrix-res-label">{c.label || "Unknown label"} · {c.country || "—"} · {c.year || "—"}</span>
                  <span className="add-matrix-res-cat">{c.catno || "—"}{c.format ? " · " + c.format : ""}</span>
                  {(typeof c.lowestPrice === "number" && c.lowestPrice > 0) && (
                    <span className="add-matrix-res-market">
                      from £{Math.round(c.lowestPrice).toLocaleString("en-GB")}
                      {typeof c.numForSale === "number" && c.numForSale > 0 ? ` · ${c.numForSale} for sale` : ""}
                    </span>
                  )}
                </span>
                <span className="add-matrix-res-score">{Math.round((c.rank || c.score) * 100)}%</span>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function PressingGuide({ onHome, onCollection }) {
  return (
    <main className="pg-page">
      <div className="pg-wrap">
        <button className="pg-back" onClick={onHome}>← Back to The Lead-In</button>

        <div className="pg-eyebrow">Collectors</div>
        <h1 className="pg-h1">How to identify your pressing</h1>
        <p className="pg-intro">
          Two copies of the same album can be worth wildly different amounts. A first pressing and a
          reissue might look almost identical on the shelf and differ by hundreds of pounds. This guide
          walks you through the clues that tell them apart, in the order that's quickest to check. You do
          not need to be an expert. Most pressings can be pinned down in a couple of minutes once you know
          where to look.
        </p>

        <div className="pg-toc">
          <span className="pg-toc-head">The quick version</span>
          <p>
            Check, in this order: the <b>matrix / runout etchings</b> in the run-out groove, the
            <b> catalogue number</b> on the label and sleeve, the <b>label design</b>, the
            <b> sleeve and inner</b> details, and finally the <b>country and year</b>. The runout is the
            single most reliable clue, so start there.
          </p>
        </div>

        {/* 1 */}
        <section className="pg-section">
          <div className="pg-num">01</div>
          <div className="pg-body">
            <h2 className="pg-h2">The matrix / runout etchings</h2>
            <p>
              In the smooth space between the last track and the label, look for small letters and numbers
              scratched or stamped into the vinyl. This is the matrix or runout, and it is the closest
              thing a record has to a fingerprint. It often identifies the exact stamper, mastering
              engineer, and pressing plant.
            </p>
            <p>
              Tilt the record under a bright light to read it. Note everything you see on both sides,
              including hand-etched initials (mastering engineers like to sign their work) and any stamped
              codes. A first pressing usually has the earliest matrix numbers; later runs add suffix
              letters or higher numbers.
            </p>
            <p className="pg-tip">
              Tip: write the runout down exactly, character for character, including spaces and symbols.
              You can then search it on Discogs to find the matching pressing.
            </p>
            <div className="pg-identifier-wrap">
              <div className="pg-identifier-head">Try it now — identify your pressing</div>
              <MatrixIdentifier />
            </div>
          </div>
        </section>

        {/* 2 */}
        <section className="pg-section">
          <div className="pg-num">02</div>
          <div className="pg-body">
            <h2 className="pg-h2">The catalogue number</h2>
            <p>
              The catalogue number appears on the label, the spine, and usually the back cover. The same
              album reissued in a different country or decade typically carries a different catalogue
              number, so matching it narrows things down fast.
            </p>
            <p>
              Watch for small differences: a prefix change, an added letter, or a stereo versus mono
              suffix. Mono and stereo versions of the same record are different pressings and can have very
              different values.
            </p>
          </div>
        </section>

        {/* 3 */}
        <section className="pg-section">
          <div className="pg-num">03</div>
          <div className="pg-body">
            <h2 className="pg-h2">The label design</h2>
            <p>
              Record labels redesigned their center labels every few years, so the artwork in the middle
              of the disc dates a pressing. Look at the label's colour, the logo style, the typeface, and
              the rim text printed around the edge.
            </p>
            <p>
              A famous example of the kind of thing to look for: text reading something like "made in" a
              particular country, a small rights-society logo, or a change from a textured to a glossy
              label. Reference photos for a given release on Discogs show exactly which label belongs to
              which pressing.
            </p>
          </div>
        </section>

        {/* 4 */}
        <section className="pg-section">
          <div className="pg-num">04</div>
          <div className="pg-body">
            <h2 className="pg-h2">The sleeve and inner</h2>
            <p>
              Sleeves carry plenty of clues. Check whether the cover opens (a gatefold) or not, how the
              edges are finished (a laminated front, a flipback edge), and what is printed on the back: the
              price code, the printer's mark, and any catalogue or order numbers.
            </p>
            <p>
              The inner sleeve matters too. An original may include a printed inner with lyrics or photos,
              while a reissue uses a plain paper or poly-lined inner. Promotional copies often have a stamp
              or a hole punched in the corner.
            </p>
          </div>
        </section>

        {/* 5 */}
        <section className="pg-section">
          <div className="pg-num">05</div>
          <div className="pg-body">
            <h2 className="pg-h2">Country and year</h2>
            <p>
              Finally, place the pressing geographically and in time. The label, the rights-society marks,
              and the catalogue prefix usually reveal the country of manufacture. Beware of dates printed
              on the sleeve: a copyright year tells you when the music was released, not when your specific
              copy was pressed. The runout and label design are better guides to the actual pressing year.
            </p>
          </div>
        </section>

        <section className="pg-cta">
          <h2 className="pg-cta-h">Still not sure?</h2>
          <p>
            That is completely normal, and it is fine to add a record to your collection without choosing a
            pressing. When you add one, just pick <b>"I'm not sure which pressing"</b>. It will sit in your
            collection unvalued until you come back and identify it using the steps above. Your collection
            view flags anything that still needs a pressing, so it is easy to pick up where you left off.
          </p>
          <button className="pg-cta-btn" onClick={onCollection}>Go to my collection →</button>
        </section>
      </div>
    </main>
  );
}

window.PressingGuide = PressingGuide;
