/* src/components/chart.jsx — print-first one-page chart + roadmap rail */

function buildSegs(chords, lyric) {
  lyric = lyric || '';
  if (!chords || chords.length === 0) return [{ chord: '', text: lyric || '\u00A0' }];
  const pts = [...chords].sort((a, b) => a.pos - b.pos);
  const segs = [];
  if (pts[0].pos > 0) segs.push({ chord: '', text: lyric.slice(0, pts[0].pos) });
  for (let i = 0; i < pts.length; i++) {
    const start = pts[i].pos;
    const end = i + 1 < pts.length ? pts[i + 1].pos : lyric.length;
    let text = lyric.slice(Math.min(start, lyric.length), Math.max(start, end));
    if (text === '') text = '\u00A0\u00A0';
    segs.push({ chord: pts[i].sym, text });
  }
  return segs;
}

// split a string into chunks of (optional leading spaces + one word), or a run of spaces
function segWords(text) {
  if (!text) return [text == null ? '' : text];
  const out = text.match(/\s*\S+|\s+/g);
  return out && out.length ? out : [text];
}

function makeTx(song) {
  const E = window.Engine;
  if (song.nashville) return (sym) => E.nashvilleChord(sym, song.origKey);
  const steps = song.transpose || 0;
  const targetKey = E.transposeKey(song.origKey, steps);
  const useFlats = E.keyUseFlats(targetKey);
  return (sym) => E.transposeChord(sym, steps, useFlats);
}

function EditableLine({ line, accent, onChords }) {
  const [edit, setEdit] = React.useState(null);   // column being edited, or null
  const [draft, setDraft] = React.useState('');
  const lyric = (line.lyric == null || line.lyric === '\u00A0') ? '' : String(line.lyric);
  const chords = line.chords || [];
  const byPos = {};
  chords.forEach(c => { byPos[c.pos] = c.sym; });
  const maxCol = Math.max(lyric.length, ...chords.map(c => (c.pos | 0) + 1), 1);
  const cells = [];
  for (let i = 0; i < maxCol; i++) cells.push(i);

  const start = (col) => { setEdit(col); setDraft(byPos[col] || ''); };
  const commit = () => {
    if (edit == null) return;
    const v = draft.trim();
    const next = chords.filter(c => c.pos !== edit);
    if (v) next.push({ sym: v, pos: edit });
    next.sort((a, b) => a.pos - b.pos);
    setEdit(null); setDraft('');
    onChords(next);
  };

  return (
    <div className="eln">
      {cells.map(i => {
        const ch = byPos[i];
        const isEdit = edit === i;
        return (
          <span className="eln__cell" key={i}>
            <span className="eln__chord">
              {isEdit ? (
                <input className="eln__in" autoFocus value={draft}
                  onChange={e => setDraft(e.target.value)}
                  onBlur={commit}
                  onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); commit(); } else if (e.key === 'Escape') { setEdit(null); setDraft(''); } }} />
              ) : ch ? (
                <button className="eln__chip" style={{ color: accent }} onClick={() => start(i)}>{ch}</button>
              ) : (
                <button className="eln__add" onClick={() => start(i)} tabIndex={-1}>+</button>
              )}
            </span>
            <span className="eln__ch2" onClick={() => start(i)}>{lyric[i] != null ? (lyric[i] === ' ' ? '\u00A0' : lyric[i]) : '\u00A0'}</span>
          </span>
        );
      })}
    </div>
  );
}

// A lyric/chord row that, in "one line" mode, shrinks just enough to avoid an orphan
// wrap (e.g. a trailing "lowest place" dropping to its own line). Measured imperatively
// at full size each render, then scaled via --lfit — no React state, so no feedback loop.
function FitRow({ className, fit, fitKey, children }) {
  const ref = React.useRef(null);
  React.useLayoutEffect(() => {
    const el = ref.current;
    if (!el) return;
    if (!fit) { el.style.removeProperty('--lfit'); return; }
    el.style.setProperty('--lfit', '1');
    const avail = el.clientWidth;
    const natural = el.scrollWidth;
    let s = 1;
    if (natural > avail + 0.5 && natural > 0) s = Math.max(0.5, avail / natural);
    el.style.setProperty('--lfit', String(Math.round(s * 1000) / 1000));
  });
  return <div className={className} ref={ref}>{children}</div>;
}

function ChartLine({ line, tx, accent, editable, onChords, fit, fitKey }) {
  if (editable && line.kind === 'pair') {
    return <EditableLine line={line} accent={accent} onChords={onChords} />;
  }
  if (line.kind === 'blank') return <div className="ln ln--blank" />;
  if (line.kind === 'bars') {
    return (
      <div className="barline">
        {line.bars.map((bar, i) => (
          <span key={i} className="bar">
            {bar.map((c, j) => <span key={j} className="ch" style={{ color: accent }}>{tx(c)}</span>)}
          </span>
        ))}
      </div>
    );
  }
  if (line.kind === 'chordrow') {
    return (
      <FitRow className="ln ln--chordrow" fit={fit} fitKey={fitKey}>
        {line.chords.map((c, i) => (
          <React.Fragment key={i}>
            {i > 0 && <span className="chsep">|</span>}
            <span className="ch ch--solo" style={{ color: accent }}>{tx(c.sym)}</span>
          </React.Fragment>
        ))}
      </FitRow>
    );
  }
  const segs = buildSegs(line.chords, line.lyric);
  // Real-lyric segments -> chord-over-word slots (wrap at spaces). Chords with NO lyric
  // beneath them ("bare" chords) -> a bar-separated chord sequence (Em | C | G) so their
  // timing reads as distinct hits instead of bunching into one chord.
  const items = [];
  segs.forEach((s, si) => {
    const bare = s.chord && (s.text === '' || /^[\u00A0]+$/.test(s.text));
    if (bare) {
      items.push({ type: 'bare', chord: s.chord, key: si + '-b' });
    } else {
      segWords(s.text).forEach((chunk, ci) => items.push({ type: 'word', chord: ci === 0 ? s.chord : '', text: chunk, key: si + '-' + ci }));
    }
  });
  const out = [];
  for (let i = 0; i < items.length;) {
    if (items[i].type === 'bare') {
      const grp = [];
      while (i < items.length && items[i].type === 'bare') { grp.push(items[i]); i++; }
      out.push(
        <span className="slot slot--seq" key={'seq' + i}>
          <span className="ch ch--seq" style={{ color: accent }}>
            {grp.map((g, gi) => (
              <React.Fragment key={gi}>{gi > 0 && <span className="chsep">|</span>}{tx(g.chord)}</React.Fragment>
            ))}
          </span>
          <span className="ly">{'\u00A0'}</span>
        </span>
      );
    } else {
      const it = items[i]; i++;
      out.push(
        <span className="slot" key={it.key}>
          <span className="ch" style={{ color: accent }}>{it.chord ? tx(it.chord) : '\u00A0'}</span>
          <span className="ly">{it.text}</span>
        </span>
      );
    }
  }
  return <FitRow className="ln" fit={fit} fitKey={fitKey}>{out}</FitRow>;
}

function SectionCard({ sec, tx, accent, chordAccent, onHide, editable, onEditLine, fit, fitKey }) {
  return (
    <div className={`sec sec--${sec.type}${editable ? ' sec--editing' : ''}`} data-screen-label={sec.label}>
      <div className="sec__head">
        <span className="sec__code" style={{ borderColor: accent, color: accent }}>{sec.code}</span>
        <span className="sec__label">{sec.label}</span>
        {onHide && <button className="sec__del" aria-label={'Remove ' + sec.label + ' from chart'} onClick={() => onHide(sec.id)}>✕</button>}
      </div>
      <div className="sec__body">
        {sec.lines.map((ln, i) => <ChartLine key={i} line={ln} tx={tx} accent={chordAccent} editable={editable} onChords={(nc) => onEditLine(sec.id, i, nc)} fit={fit} fitKey={fitKey} />)}
      </div>
    </div>
  );
}

const DYN_LABEL = { p: 'piano (soft)', mp: 'mezzo-piano', mf: 'mezzo-forte', f: 'forte (loud)', ff: 'fortissimo' };

function RoadmapRail({ song, sections, accent }) {
  const byId = {};
  sections.forEach(s => { byId[s.id] = s; });
  const rm = song.roadmap || [];
  return (
    <aside className="rail">
      <div className="rail__title">Road Map</div>
      <ol className="rail__list">
        {rm.map((step, i) => {
          const s = byId[step.sectionId];
          if (!s) return null;
          return (
            <li key={i} className="step">
              <span className="step__code" style={{ borderColor: accent, color: accent }}>
                {s.code}{step.repeat > 1 ? <em>×{step.repeat}</em> : null}
              </span>
              <span className="step__meta">
                <span className="step__name">{s.label}</span>
                {(step.dyn || step.cue) && (
                  <span className="step__cue">
                    {step.dyn ? <b className="dyn" style={{ color: accent }}>{step.dyn}</b> : null}
                    {step.cue ? <span>{step.cue}</span> : null}
                  </span>
                )}
              </span>
            </li>
          );
        })}
      </ol>
      <div className="rail__legend">
        <span><b style={{ color: accent }}>p</b> soft</span>
        <span><b style={{ color: accent }}>mp</b></span>
        <span><b style={{ color: accent }}>mf</b></span>
        <span><b style={{ color: accent }}>f</b> loud</span>
      </div>
    </aside>
  );
}

function uniqueChords(sections, tx, nashville) {
  if (nashville) return [];
  const seen = new Set();
  const order = [];
  const add = (sym) => {
    const d = tx(sym);
    if (!seen.has(d)) { seen.add(d); order.push(d); }
  };
  sections.forEach(s => s.lines.forEach(ln => {
    if (ln.kind === 'pair' || ln.kind === 'chordrow') (ln.chords || []).forEach(c => { if (!c.annot) add(c.sym); });
    if (ln.kind === 'bars') ln.bars.forEach(b => b.forEach(sym => { if (window.Engine.parseChord(sym)) add(sym); }));
  }));
  return order;
}

function orderSections(sections, order) {
  if (!order || !order.length) return sections;
  const byId = {};
  sections.forEach(s => { byId[s.id] = s; });
  const out = [];
  order.forEach(id => { if (byId[id]) out.push(byId[id]); });
  sections.forEach(s => { if (!order.includes(s.id)) out.push(s); }); // any new/unlisted sections
  return out;
}

function Chart({ song, onHideSection, editable, onEditLine }) {
  const mono = song.mono !== false;             // black & white by default
  const ordered = orderSections(song.sections || [], song.sectionOrder);
  const hidden = song.hiddenSections || [];
  const sections = ordered.filter(s => !hidden.includes(s.id));
  const tx = makeTx(song);
  const accent = mono ? '#1c1c22' : (song.accent || 'var(--accent)');
  const chordAccent = mono ? '#1c1c22' : (song.chordColor || '#245f91');
  const targetKey = song.nashville ? 'Nashville' : window.Engine.transposeKey(song.origKey, song.transpose || 0);
  const chords = uniqueChords(sections, tx, song.nashville);
  const railSide = ['left', 'right', 'top', 'bottom'].includes(song.railSide) ? song.railSide : 'right';
  const showRail = song.railSide !== 'off' && (song.roadmap || []).length > 0;
  const fit = song.lineFit !== false;
  const fitKey = [song.cols, song.textScale, song.chordSize, song.railScale, song.railSide, song.lineSpace, song.secSpace, song.transpose, song.nashville, song.lineFit, (song.raw || '').length].join('|');

  const pageStyle = {
    '--cols': song.cols || 2,
    '--text-scale': song.textScale || 1,
    '--ch-size': song.chordSize || 1,
    '--line-space': song.lineSpace || 1,
    '--sec-space': song.secSpace || 1,
    '--rail-scale': song.railScale || 1,
  };
  if (mono) pageStyle['--paper'] = '#ffffff';

  return (
    <div className={`page${mono ? ' page--mono' : ''}${fit ? ' page--fit' : ''}`} style={pageStyle} data-screen-label="Chart">
      <header className="chead">
        <div className="chead__main">
          <h1 className="chead__title">{song.title || 'Untitled'}</h1>
          <div className="chead__sub">{song.artist}</div>
          {song.writers ? <div className="chead__credits">Written by {song.writers}</div> : null}
          {song.copyrightNotice ? <div className="chead__credits">{song.copyrightNotice}</div> : null}
          {song.scripture ? <div className="chead__scripture">{song.scripture}</div> : null}
        </div>
        <div className="chead__meta">
          <span className="meta"><label>Key</label><b>{targetKey}{song.nashville ? '' : (song.transpose ? ` (orig ${song.origKey})` : '')}</b></span>
          {song.bpm ? <span className="meta"><label>Tempo</label><b>{song.bpm} bpm</b></span> : null}
          {song.time ? <span className="meta"><label>Time</label><b>{song.time}</b></span> : null}
          {song.ccli ? <span className="meta"><label>CCLI</label><b>{song.ccli}</b></span> : null}
        </div>
      </header>

      <div className={`cbody cbody--${showRail ? railSide : 'off'}`}>
        {showRail && <RoadmapRail song={song} sections={sections} accent={accent} />}
        <div className="sections">
          {sections.map(s => <SectionCard key={s.id} sec={s} tx={tx} accent={accent} chordAccent={chordAccent} onHide={onHideSection} editable={editable} onEditLine={onEditLine} fit={fit} fitKey={fitKey} />)}
        </div>
      </div>

      {song.diagrams && chords.length > 0 && (
        <div className="diags">
          {chords.map((name, i) => (
            <window.ChordDiagram key={i} name={name} shape={window.AppData.SHAPES[name]} accent={chordAccent} />
          ))}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { Chart, makeTx, buildSegs, DYN_LABEL });
