/* global React, window */
// Worship Planner — Solo / Ensemble tab view.
// Renders window.SOLO[sunday.id] for the current Sunday, mirroring the hymns
// and artwork layouts: a "for the day" strip for pieces keyed to the whole
// service (general solos + ensembles), then one column per reading.
//
// Per the standing rule, Psalms are omitted from solos/ensembles — so the
// Psalm column is shown ONLY when it actually has pieces (e.g. festivals like
// All Saints). OT / Epistle / Gospel always render.
//
// Exposed as window.SoloView; planner.jsx mounts it on the "solo" tab.
// Props: { sunday }

(function () {
  const { useState } = React;

  const SLOTS = ["ot", "psalm", "epistle", "gospel"];
  const INITIAL_VISIBLE = 6;

  // Short label shown on each piece's type rail.
  const TYPE_SHORT = {
    Vocal: "Vocal Solo",
    Instrumental: "Instrumental Solo",
    Ensemble: "Orchestra Ensemble",
    Seasonal: "Seasonal",
  };

  function SoloCard({ piece, passage }) {
    const type = piece.type || "Vocal";
    return (
      <div className="wp-solo-card" data-passage={passage} data-type={type}>
        <div className="wp-solo-rail">
          <span className="wp-solo-type">{TYPE_SHORT[type] || type}</span>
        </div>
        <div className="wp-solo-body">
          <div className="wp-solo-title">
            {piece.title || piece.detail}
            {piece.titleAlt &&
              <span className="wp-solo-alt"> ({piece.titleAlt})</span>}
          </div>
          {piece.title && piece.detail &&
            <p className="wp-solo-detail">{piece.detail}</p>}
          {(piece.owned || piece.tag) &&
            <div className="wp-solo-foot">
              {piece.owned && <span className="wp-solo-chip is-owned">Owned</span>}
              {piece.tag && <span className="wp-solo-chip">{piece.tag}</span>}
            </div>}
        </div>
      </div>);
  }

  // Passage header — same structure/classes as the hymns + artwork tabs so the
  // typography and color-coded tag match exactly (no skip toggle here).
  function SoloPassageHead({ pkey, reading, label }) {
    return (
      <section className="wp-passage" data-passage={pkey}>
        <div className="wp-passage-marker">
          <span className="wp-passage-tag">{label}</span>
        </div>
        <div className="wp-passage-body">
          <div className="wp-passage-ref">{reading?.ref}</div>
          {reading?.theme && <p className="wp-passage-theme">{reading.theme}</p>}
        </div>
      </section>);
  }

  function SoloColumn({ pkey, label, reading, items }) {
    const [expanded, setExpanded] = useState(false);
    const count = items.length;
    const overflow = count - INITIAL_VISIBLE;
    const visible = expanded ? items : items.slice(0, INITIAL_VISIBLE);

    return (
      <article className="wp-solo-col" data-passage={pkey}>
        <SoloPassageHead pkey={pkey} label={label} reading={reading} />
        {count === 0 ?
          <div className="wp-solo-empty">
            <p className="wp-solo-empty-text">
              {pkey === "psalm"
                ? "Psalm solos omitted by convention."
                : "No solo or ensemble indexed for this reading."}
            </p>
          </div> :
          <>
            <div className="wp-solo-list">
              {visible.map((p, i) => <SoloCard key={i} piece={p} passage={pkey} />)}
            </div>
            {overflow > 0 &&
              <button className="wp-disclosure wp-solo-more" onClick={() => setExpanded((v) => !v)}>
                <span className={`wp-disclosure-caret ${expanded ? "on" : ""}`}>
                  <svg width="9" height="9" viewBox="0 0 9 9"><path d="M2 2 L7 4.5 L2 7 Z" fill="currentColor" /></svg>
                </span>
                {expanded ? "Show fewer" : `Show ${overflow} more`}
                {!expanded && <span className="wp-disclosure-count">{count}</span>}
                <span className="wp-disclosure-hint">
                  {expanded ? "collapse to the first six" : "more pieces for this reading"}
                </span>
              </button>}
          </>}
      </article>);
  }

  function SoloWholeStrip({ items }) {
    if (!items || items.length === 0) return null;
    return (
      <section className="wp-solo-whole">
        <div className="wp-solo-whole-h">
          <span className="wp-solo-whole-h-l">For the day</span>
          <span className="wp-solo-whole-h-s">General & topical solos · ensembles — not keyed to one reading</span>
        </div>
        <div className="wp-solo-whole-grid">
          {items.map((p, i) => <SoloCard key={i} piece={p} passage="whole" />)}
        </div>
      </section>);
  }

  function SoloView({ sunday, track, changeTrack, rclVersion, changeRclVersion, hidden }) {
    const used = hidden || new Set();
    const entry = (window.SOLO || {})[sunday.id];
    const raw = entry || { ot: [], psalm: [], epistle: [], gospel: [], general: [] };

    // Lectionary-track + RCL-version filter — shared helpers from planner.jsx.
    // Pieces may carry track: "semi" | "comp" | "cct"; untagged pieces show
    // on every track.
    const effTrack = window.effTrackFor ? window.effTrackFor(sunday.id, track, rclVersion) : (track || "n/a");
    const allow = (p) => !window.trackAllows || window.trackAllows(p.track, effTrack);
    const slots = {};
    for (const k of [...SLOTS, "general"]) slots[k] = (raw[k] || []).filter(allow);

    const total = SLOTS.reduce((n, p) => n + ((slots[p] || []).length), 0) +
      ((slots.general || []).length);

    if (!entry || total === 0) {
      return (
        <section className="wp-solo-empty" style={{ marginTop: 8 }}>
          <p className="wp-solo-empty-text">
            No solos or ensembles have been indexed for {sunday.day} yet.
          </p>
        </section>);
    }

    // Render OT / Epistle / Gospel always; Psalm only when it carries pieces.
    // Any reading set aside in the shared "Scripture used" bar is dropped.
    const cols = SLOTS.filter((p) => (p !== "psalm" || (slots.psalm || []).length > 0) && !used.has(p));

    return (
      <div className="wp-solo">
        <SoloWholeStrip items={slots.general || []} />

        <div className="wp-solo-cols-h">
          <span>Solos &amp; ensembles by reading</span>
          <span className="wp-solo-cols-h-hint">Vocal · instrumental · ensemble — direct, thematic &amp; atmospheric fits</span>
        </div>
        <div className="wp-solo-cols" data-cols={cols.length}>
          {cols.map((p) =>
            <SoloColumn key={p} pkey={p}
              label={window.PASSAGE_LABELS[p]}
              reading={window.readingForTrack ? window.readingForTrack(sunday, p, effTrack) : sunday.readings[p]}
              items={slots[p] || []} />)}
        </div>
      </div>);
  }

  window.SoloView = SoloView;
})();
