// Story rails + modal reader — red/black. Left: editorial investigations.
// Right: live DOJ enforcement cases (Medicaid first, then newest), then analysis.

function fwRailCases() {
  const nameByAbbr = {};
  Object.entries(window.STATE_ABBR_BY_NAME || {}).forEach(([n, a]) => { nameByAbbr[a] = n; });
  const out = [];
  Object.entries(window.CASES_BY_STATE || {}).forEach(([abbr, list]) => (list || []).forEach(c => {
    out.push({ ...c, __locator:
      (c.county_name ? c.county_name.toUpperCase() + ' COUNTY · ' : '') +
      (nameByAbbr[abbr] || abbr).toUpperCase() });
  }));
  out.sort((a, b) => {
    const am = (a.program_tags || []).includes('medicaid') ? 0 : 1;
    const bm = (b.program_tags || []).includes('medicaid') ? 0 : 1;
    if (am !== bm) return am - bm;
    return (b.date || '').localeCompare(a.date || '');
  });
  return out;
}

function StoryRail({ side, stories, onOpen }) {
  const mine = stories.filter(s => s.side === side);
  const cases = side === 'right' ? fwRailCases() : [];
  const hdr = {
    fontFamily: 'ui-monospace, monospace', fontSize: 10, fontWeight: 700,
    color: '#ff3030', letterSpacing: 2.5,
    paddingBottom: 12, borderBottom: '1px solid rgba(255,40,40,0.2)',
  };
  return (
    <div style={{
      width: 280, flexShrink: 0,
      background: 'linear-gradient(180deg, #0a0000 0%, #050000 100%)',
      borderLeft:  side === 'right' ? '1px solid rgba(255,40,40,0.25)' : 'none',
      borderRight: side === 'left'  ? '1px solid rgba(255,40,40,0.25)' : 'none',
      padding: '24px 20px', display: 'flex', flexDirection: 'column',
      gap: 12, overflowY: 'auto',
    }}>
      {cases.length > 0 && (
        <React.Fragment>
          <div style={hdr}>// DOJ ENFORCEMENT · LIVE</div>
          <div>
            {cases.map((c, i) => <CaseRow key={'case' + i} c={c} locator={c.__locator} />)}
          </div>
        </React.Fragment>
      )}
      <div style={{ ...hdr, marginTop: cases.length ? 10 : 0 }}>
        {side === 'left' ? '// INVESTIGATIONS' : '// ANALYSIS'}
      </div>
      {mine.map(s => (
        <button key={s.id} onClick={() => onOpen(s)} style={{
          background: 'rgba(20,0,0,0.7)',
          border: '1px solid rgba(255,40,40,0.15)',
          padding: '14px 16px', textAlign: 'left', cursor: 'pointer',
          color: '#f0dada', transition: 'all 0.15s',
          fontFamily: '"Space Grotesk", sans-serif',
        }}
          onMouseEnter={e => {
            e.currentTarget.style.borderColor = '#ff3030';
            e.currentTarget.style.background = 'rgba(40,0,0,0.8)';
          }}
          onMouseLeave={e => {
            e.currentTarget.style.borderColor = 'rgba(255,40,40,0.15)';
            e.currentTarget.style.background = 'rgba(20,0,0,0.7)';
          }}>
          <div style={{
            display: 'flex', justifyContent: 'space-between',
            fontFamily: 'ui-monospace, monospace', fontSize: 9, fontWeight: 700,
            letterSpacing: 1.5, marginBottom: 10,
          }}>
            <span style={{ color: '#ff3030' }}>
              {s.tag.toUpperCase()}
              {s.sample ? <span style={{ color:'#000', background:'#ffa020', marginLeft:6, padding:'1px 4px' }}>SAMPLE</span> : null}
            </span>
            <span style={{ color: 'rgba(200,100,100,0.55)' }}>{s.date}</span>
          </div>
          <div style={{
            fontSize: 14, fontWeight: 800, lineHeight: 1.25,
            marginBottom: 8, color: '#fff', letterSpacing: -0.2,
          }}>{s.title}</div>
          <div style={{
            fontSize: 12, lineHeight: 1.5, fontWeight: 500,
            color: 'rgba(220,180,180,0.7)',
          }}>{s.dek}</div>
        </button>
      ))}
    </div>
  );
}

function StoryModal({ story, onClose }) {
  if (!story) return null;
  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 200,
      background: 'rgba(0,0,0,0.88)', backdropFilter: 'blur(10px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 40,
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: 'min(720px, 100%)', maxHeight: '86vh', overflowY: 'auto',
        background: '#0a0000', border: '1px solid #ff2020',
        padding: '44px 56px', color: '#f0dada',
        boxShadow: '0 40px 100px rgba(0,0,0,0.9), 0 0 80px rgba(255,40,40,0.15)',
        fontFamily: '"Space Grotesk", sans-serif',
      }}>
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          fontFamily: 'ui-monospace, monospace', fontSize: 10, fontWeight: 700,
          letterSpacing: 2.5, marginBottom: 24,
        }}>
          <span style={{ color: '#ff3030' }}>
            {story.tag.toUpperCase()} · {(story.date || '').toUpperCase()}
            {story.sample ? <span style={{ color:'#000', background:'#ffa020', marginLeft:8, padding:'2px 6px' }}>SAMPLE CONTENT</span> : null}
          </span>
          <button onClick={onClose} style={{
            background: 'transparent', border: '1px solid rgba(255,40,40,0.4)',
            color: '#ff5050', padding: '6px 12px', cursor: 'pointer',
            fontFamily: 'inherit', fontSize: 10, fontWeight: 700, letterSpacing: 1.5,
          }}>CLOSE ✕</button>
        </div>
        <h1 style={{
          fontSize: 38, lineHeight: 1.1, fontWeight: 800, letterSpacing: -1,
          margin: '0 0 18px', color: '#fff',
        }}>{story.title}</h1>
        <div style={{
          fontSize: 18, lineHeight: 1.4, color: '#ff7070', fontWeight: 600,
          marginBottom: 32, paddingBottom: 24, borderBottom: '1px solid rgba(255,40,40,0.25)',
        }}>{story.dek}</div>
        {(story.body || []).map((p, i) => (
          <p key={i} style={{
            fontSize: 15, lineHeight: 1.75, marginBottom: 18, fontWeight: 400,
            color: 'rgba(230,200,200,0.88)',
          }}>{p}</p>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { StoryRail, StoryModal });
