/* ===========================================================
   TheArtist — section II½, "The artist".

   Three reader questions the dossiers never answered, gathered into one section
   because they are all versions of the same question ("who made this, and where
   were they when they did?"):

     1. LIFE      — born, died, what of, who they were with, children, estate.
                    A dossier that says "he died on September 18, 1970 at age 27"
                    and stops is conspicuously silent on the most-asked question
                    about its own subject.
     2. CATALOGUE — where this album sits in the artist's own run of records, so a
                    newcomer can see whether they are looking at a debut, a peak
                    or a late turn.
     3. LINEUP    — who actually played, who replaced whom, and who is still
                    alive. The death years were already in the data, buried inside
                    prose role descriptions.

   EVIDENCE DISCIPLINE
   Biography invites invention, and several of these artists are living, so the
   schema is built to make a thin entry look thin instead of confident:
     * every claim carries `status` — "documented" | "reported" | "disputed"
     * anything not established is listed in `notDocumented` and RENDERED, so the
       absence is visible to the reader rather than quietly filled in
     * `sources` names where a claim comes from
   A section with no `life` block simply does not render that block. Nothing here
   guesses, and nothing infers a private fact from a public one.
   =========================================================== */

const { useState: useArtState } = React;

function statusNote(status) {
  if (!status || status === "documented") return null;
  if (status === "reported") return "reported";
  if (status === "disputed") return "disputed";
  return status;
}

/* ---- 1. Life ------------------------------------------------------------- */
function ArtistLife({ life }) {
  if (!life) return null;
  const rows = [];
  if (life.born) rows.push(["Born", life.born]);
  if (life.died) rows.push(["Died", life.died]);
  if (life.livingNote) rows.push(["Living", life.livingNote]);

  return (
    <div className="ta-life">
      {rows.length > 0 && (
        <dl className="ta-vitals">
          {rows.map(([k, v]) => (
            <div key={k}><dt>{k}</dt><dd>{v}</dd></div>
          ))}
        </dl>
      )}

      {life.causeOfDeath && (
        <div className="ta-block">
          <h5>Cause of death</h5>
          <p className="ta-lead">{life.causeOfDeath.summary}</p>
          {life.causeOfDeath.detail && <p>{life.causeOfDeath.detail}</p>}
          {life.causeOfDeath.verdict && (
            <p className="ta-verdict"><b>Official finding</b> {life.causeOfDeath.verdict}</p>
          )}
        </div>
      )}

      {life.relationships && life.relationships.length > 0 && (
        <div className="ta-block">
          <h5>Partners and marriages</h5>
          <ul className="ta-rel">
            {life.relationships.map((r, i) => (
              <li key={i}>
                <span className="ta-rel-name">{r.name}</span>
                {r.years && <span className="ta-rel-years">{r.years}</span>}
                {statusNote(r.status) && <span className="ta-flag">{statusNote(r.status)}</span>}
                {r.detail && <p>{r.detail}</p>}
              </li>
            ))}
          </ul>
        </div>
      )}

      {life.children && (
        <div className="ta-block">
          <h5>Children</h5>
          <p>{life.children.summary}</p>
          {life.children.detail && <p>{life.children.detail}</p>}
        </div>
      )}

      {life.estate && (
        <div className="ta-block">
          <h5>Estate and afterlife</h5>
          <p>{life.estate}</p>
        </div>
      )}

      {/* The point of the section: say what is NOT known, rather than leaving a
          reader to assume the silence means something. */}
      {life.notDocumented && life.notDocumented.length > 0 && (
        <div className="ta-block ta-notknown">
          <h5>Not established</h5>
          <ul>
            {life.notDocumented.map((n, i) => <li key={i}>{n}</li>)}
          </ul>
        </div>
      )}

      {life.sources && life.sources.length > 0 && (
        <p className="ta-sources"><b>Sources</b> {life.sources.join(" · ")}</p>
      )}
    </div>
  );
}

/* ---- 2. Where this album sits in the catalogue --------------------------- */
function ArtistDiscography({ discography, slug }) {
  if (!discography || !discography.releases || !discography.releases.length) return null;
  const [showAll, setShowAll] = useArtState(false);

  const releases = discography.releases;
  const thisIdx = releases.findIndex((r) => r.isThis || r.slug === slug);

  // Long catalogues collapse around the album in hand: a reader wants to see
  // where it falls, not read a complete bibliography.
  const WINDOW = 3;
  let shown = releases;
  let trimmedBefore = 0, trimmedAfter = 0;
  if (!showAll && thisIdx >= 0 && releases.length > WINDOW * 2 + 3) {
    const from = Math.max(0, thisIdx - WINDOW);
    const to = Math.min(releases.length, thisIdx + WINDOW + 1);
    shown = releases.slice(from, to);
    trimmedBefore = from;
    trimmedAfter = releases.length - to;
  }

  return (
    <div className="ta-disco">
      {discography.summary && <p className="ta-lead">{discography.summary}</p>}
      {trimmedBefore > 0 && (
        <button className="ta-more" onClick={() => setShowAll(true)}>
          {trimmedBefore} earlier release{trimmedBefore === 1 ? "" : "s"}
        </button>
      )}
      <ol className="ta-disco-list">
        {shown.map((r, i) => {
          const isThis = r.isThis || r.slug === slug;
          return (
            <li key={r.title + i} className={isThis ? "ta-d-this" : undefined}>
              <span className="ta-d-year">{r.year}</span>
              <span className="ta-d-title">
                {r.title}
                {isThis && <span className="ta-d-marker">this album</span>}
              </span>
              {r.note && <span className="ta-d-note">{r.note}</span>}
            </li>
          );
        })}
      </ol>
      {trimmedAfter > 0 && (
        <button className="ta-more" onClick={() => setShowAll(true)}>
          {trimmedAfter} later release{trimmedAfter === 1 ? "" : "s"}
        </button>
      )}
      {discography.note && <p className="ta-disco-note">{discography.note}</p>}
    </div>
  );
}

/* ---- 3. Lineup, with status ---------------------------------------------- */
const STATUS_LABEL = {
  living: "Living",
  died: "Died",
  disbanded: "—",
  unknown: "Not established",
};

function ArtistLineup({ lineup }) {
  if (!lineup || !lineup.members || !lineup.members.length) return null;
  return (
    <div className="ta-lineup">
      {lineup.summary && <p className="ta-lead">{lineup.summary}</p>}
      <ul className="ta-members">
        {lineup.members.map((m, i) => (
          <li key={i} className={"ta-m ta-m-" + (m.status || "unknown")}>
            <div className="ta-m-top">
              <span className="ta-m-name">{m.name}</span>
              <span className="ta-m-role">{m.role}</span>
            </div>
            <div className="ta-m-meta">
              {m.tenure && <span className="ta-m-tenure">{m.tenure}</span>}
              <span className={"ta-m-status s-" + (m.status || "unknown")}>
                {m.status === "died" && m.died
                  ? "Died " + m.died
                  : (STATUS_LABEL[m.status] || STATUS_LABEL.unknown)}
              </span>
            </div>
            {m.note && <p className="ta-m-note">{m.note}</p>}
          </li>
        ))}
      </ul>
      {lineup.changes && lineup.changes.length > 0 && (
        <div className="ta-block">
          <h5>Line-up changes</h5>
          <ol className="ta-changes">
            {lineup.changes.map((c, i) => (
              <li key={i}>
                <span className="ta-c-when">{c.when}</span>
                <span className="ta-c-what">{c.what}</span>
              </li>
            ))}
          </ol>
        </div>
      )}
    </div>
  );
}

/* ---- the section -------------------------------------------------------- */
function TheArtist({ profile, slug }) {
  if (!profile) return null;
  const tabs = [];
  if (profile.life) tabs.push(["life", profile.life.tabLabel || "Life and death"]);
  if (profile.discography && profile.discography.releases) tabs.push(["disco", "Where this album sits"]);
  if (profile.lineup && profile.lineup.members) tabs.push(["lineup", "Who played on it"]);
  if (!tabs.length) return null;

  const [tab, setTab] = useArtState(tabs[0][0]);

  return (
    <div className="the-artist">
      {tabs.length > 1 && (
        <div className="ta-tabs">
          {tabs.map(([k, label]) => (
            <button key={k} className={tab === k ? "ta-tab active" : "ta-tab"} onClick={() => setTab(k)}>
              {label}
            </button>
          ))}
        </div>
      )}
      {tab === "life" && <ArtistLife life={profile.life} />}
      {tab === "disco" && <ArtistDiscography discography={profile.discography} slug={slug} />}
      {tab === "lineup" && <ArtistLineup lineup={profile.lineup} />}
    </div>
  );
}

Object.assign(window, { TheArtist, ArtistLife, ArtistDiscography, ArtistLineup });
