// bu/v8-rail.jsx — AI補助あり版：左固定カード（対象者と主要状態）＋簡易推移
//  ・総合スコアは「本人の変化」のみ（部署/班/組織/過去平均は表示しない）
//  ・差分は必ず「前回比」として扱う（前月比ではない）
//  ・簡易推移は直近6回・縦軸1〜5固定・中立色・最新値を強調・未回答は連続させない
const { Face } = window;
const { P, DeltaChip } = window.V4;

// 注意度トーン（人物評価ではなく、今回の対話・フォローの優先度）
const S8 = {
  plain: { wash: '#f5f8fc', head: 'linear-gradient(180deg,#eaf2fc 0%,#fff 90%)', line: '#e2e9f2', fg: '#3a6ea8', label: null, note: '黄・赤の注意喚起はありません' },
  attn: { wash: '#fcf9f0', head: 'linear-gradient(180deg,#faf1d8 0%,#fff 90%)', line: '#eee3c8', fg: '#8a6b12', label: '確認事項あり', note: '意識して確認してほしい項目があります' },
  follow: { wash: '#fdf5f6', head: 'linear-gradient(180deg,#fae4e7 0%,#fff 90%)', line: '#f1d6db', fg: '#ad3348', label: '要フォロー', note: 'しっかりフォローしてほしい内容があります' },
  nodata: { wash: '#f5f6f7', head: 'linear-gradient(180deg,#eaebed 0%,#fff 90%)', line: '#e3e5e8', fg: '#6b7280', label: 'データ不足', note: '今回のアンケートが未回答です' },
};

// 直近6回の回答（未回答・期限超過・遅延回答を含む）
const R8 = {
  rounds: [
    { m: '1月', date: '2026/01/20', v: 3.6 },
    { m: '2月', date: '2026/02/18', v: 3.5 },
    { m: '3月', missing: true, deadline: '2026/03/31' },
    { m: '4月', date: '2026/04/20', v: 3.7 },
    { m: '5月', date: '2026/05/19', v: 3.8 },
    { m: '6月', date: '2026/06/28', v: 3.9, late: 3, deadline: '2026/06/25' },
  ],
  score: 3.9, delta: 0.1,
};
const ROUNDS_OK = [
  { m: '1月', date: '2026/01/20', v: 3.6 }, { m: '2月', date: '2026/02/18', v: 3.8 },
  { m: '3月', date: '2026/03/19', v: 3.7 }, { m: '4月', date: '2026/04/20', v: 3.9 },
  { m: '5月', date: '2026/05/19', v: 4.0 }, { m: '6月', date: '2026/06/22', v: 4.2 },
];
const ROUNDS_BAD = [
  { m: '1月', date: '2026/01/20', v: 3.8 }, { m: '2月', date: '2026/02/18', v: 3.5 },
  { m: '3月', missing: true, deadline: '2026/03/31' }, { m: '4月', date: '2026/04/20', v: 3.4 },
  { m: '5月', date: '2026/05/19', v: 3.2 }, { m: '6月', date: '2026/06/28', v: 2.4, late: 3, deadline: '2026/06/25' },
];
const ROUNDS_NODATA = [
  { m: '1月', date: '2026/01/20', v: 3.6 }, { m: '2月', date: '2026/02/18', v: 3.5 },
  { m: '3月', missing: true, deadline: '2026/03/31' }, { m: '4月', date: '2026/04/20', v: 3.7 },
  { m: '5月', date: '2026/05/19', v: 3.8 }, { m: '6月', missing: true, deadline: '2026/06/25' },
];

const NEU = '#6d7684';

if (typeof document !== 'undefined' && !document.getElementById('v8-styles')) {
  const s = document.createElement('style');
  s.id = 'v8-styles';
  s.textContent = '.v4 .lbl8{white-space:nowrap;flex-shrink:0}';
  document.head.appendChild(s);
}

// 簡易推移：縦軸1〜5固定・中立色・最新値を強調・未回答は線をつながない
function MiniTrend({ rounds, w = 248, h = 76, id, sparse = false }) {
  const [hi, setHi] = React.useState(null);
  const padT = 14, padB = 21, padX = 11;
  const yv = (v) => (h - padB) - ((v - 1) / 4) * (h - padT - padB);
  const xs = rounds.map((_, i) => padX + (i / (rounds.length - 1)) * (w - 2 * padX));
  const segs = []; let run = [];
  rounds.forEach((r, i) => { if (r.v != null) run.push(i); else { if (run.length) segs.push(run); run = []; } });
  if (run.length) segs.push(run);
  const answered = rounds.map((r, i) => (r.v != null ? i : -1)).filter((i) => i >= 0);
  const last = answered[answered.length - 1];
  const gid = `mt-${id}`;
  const tip = hi != null ? rounds[hi] : null;
  return (
    <div style={{ position: 'relative', width: w }}>
      <svg width={w} height={h} viewBox={`0 0 ${w} ${h}`} style={{ display: 'block' }}>
        <defs>
          <linearGradient id={gid} x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={NEU} stopOpacity="0.16" />
            <stop offset="100%" stopColor={NEU} stopOpacity="0" />
          </linearGradient>
        </defs>
        {[5, 4, 3, 2, 1].map((v) => (
          <line key={v} x1="0" x2={w} y1={yv(v)} y2={yv(v)} stroke="#edeff3" strokeWidth="1" />
        ))}
        <text x="0" y={yv(5) - 3} style={{ fontSize: 8.5, fill: P.ghost }}>5</text>
        <text x="1" y={yv(1) + 9} style={{ fontSize: 8.5, fill: P.ghost }}>1</text>
        {segs.map((s, k) => {
          const next = segs[k + 1];
          if (!next) return null;
          const a = s[s.length - 1], b = next[0];
          return <line key={`g${k}`} x1={xs[a]} y1={yv(rounds[a].v)} x2={xs[b]} y2={yv(rounds[b].v)} stroke="#c9ced6" strokeWidth="1.4" strokeDasharray="2.5 3.5" />;
        })}
        {segs.map((s, k) => {
          if (s.length < 2) return null;
          const pts = s.map((i) => `${xs[i].toFixed(1)},${yv(rounds[i].v).toFixed(1)}`).join(' ');
          return (
            <g key={k}>
              <polygon points={`${xs[s[0]].toFixed(1)},${h - padB} ${pts} ${xs[s[s.length - 1]].toFixed(1)},${h - padB}`} fill={`url(#${gid})`} />
              <polyline points={pts} fill="none" stroke={NEU} strokeWidth="1.9" strokeLinejoin="round" strokeLinecap="round" />
            </g>
          );
        })}
        {rounds.map((r, i) => (r.missing ? (
          <line key={`m${i}`} x1={xs[i]} x2={xs[i]} y1={padT - 4} y2={h - padB} stroke="#d6dae1" strokeWidth="1" strokeDasharray="2 3" />
        ) : null))}
        {answered.map((i) => (i === last ? null : (
          <circle key={i} cx={xs[i]} cy={yv(rounds[i].v)} r={hi === i ? 3.6 : 2.5} fill="#fff" stroke={NEU} strokeWidth="1.7" />
        )))}
        {last != null && (
          <g>
            <circle cx={xs[last]} cy={yv(rounds[last].v)} r="7.5" fill={P.ink} opacity="0.09" />
            <circle cx={xs[last]} cy={yv(rounds[last].v)} r="4.2" fill={P.ink} stroke="#fff" strokeWidth="1.6" />
          </g>
        )}
        {rounds.map((r, i) => {
          if (sparse && !(i === 0 || i === last || i === Math.floor((rounds.length - 1) / 2))) return null;
          return (
            <text key={`t${i}`} x={xs[i]} y={h - 6} textAnchor="middle" className="tnum"
              style={{ fontSize: sparse ? 11 : 9.5, fontWeight: i === last ? 800 : 600, fill: r.missing ? P.muted : i === last ? P.ink : P.muted }}>{r.m}</text>
          );
        })}
        {rounds.map((r, i) => (
          <rect key={`h${i}`} x={xs[i] - (w / rounds.length) / 2} y="0" width={w / rounds.length} height={h} fill="transparent"
            onMouseEnter={() => setHi(i)} onMouseLeave={() => setHi(null)} style={{ cursor: 'pointer' }} />
        ))}
      </svg>
      {tip && (
        <div style={{ position: 'absolute', left: Math.min(Math.max(xs[hi], 48), w - 48), top: -4, transform: 'translate(-50%,-100%)', background: '#fff', border: `1px solid ${P.line}`, borderRadius: 9, boxShadow: '0 8px 20px -8px rgba(18,22,30,.3)', padding: '7px 11px', whiteSpace: 'nowrap', pointerEvents: 'none', zIndex: 3 }}>
          {tip.missing ? (
            <>
              <div className="tnum" style={{ fontSize: 11.5, fontWeight: 800, color: P.muted }}>{tip.m} 未回答</div>
              <div className="tnum" style={{ fontSize: 10.5, color: P.faint, marginTop: 2 }}>期限 {tip.deadline} 超過</div>
            </>
          ) : (
            <>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
                <span className="tnum" style={{ fontSize: 14, fontWeight: 800, color: P.ink }}>{tip.v.toFixed(1)}</span>
                <span className="tnum" style={{ fontSize: 10, color: P.ghost }}>/ 5.0</span>
              </div>
              <div className="tnum" style={{ fontSize: 10.5, color: P.faint, marginTop: 2 }}>{tip.date} 回答{tip.late ? ` ・ ${tip.late}日遅れ` : ''}</div>
            </>
          )}
        </div>
      )}
    </div>
  );
}

function ScoreHelp() {
  const [open, setOpen] = React.useState(false);
  return (
    <span style={{ position: 'relative', display: 'inline-flex' }}>
      <button onClick={() => setOpen((v) => !v)} aria-label="総合スコアの算出方法" style={{ all: 'unset', cursor: 'pointer', width: 15, height: 15, borderRadius: 15, border: `1px solid ${P.ghost}`, color: P.faint, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 10, fontWeight: 800, lineHeight: 1 }}>i</button>
      {open && (
        <div style={{ position: 'absolute', top: 22, left: -8, width: 226, background: '#fff', border: `1px solid ${P.line}`, borderRadius: 11, boxShadow: '0 14px 34px -12px rgba(18,22,30,.34)', padding: '13px 15px', zIndex: 5, textAlign: 'left' }}>
          <div style={{ fontSize: 11.5, fontWeight: 800, color: P.ink, letterSpacing: '.02em' }}>総合スコアについて</div>
          <p style={{ margin: '7px 0 0', fontSize: 11.5, lineHeight: 1.75, color: P.muted, fontWeight: 500 }}>アンケート全8設問の平均値（5段階）です。未回答の設問は平均に含みません。差分は直前の<b style={{ color: P.ink2 }}>回答回</b>との比較（前回比）で、回答間隔には左右されません。</p>
          <button className="tlnk" onClick={() => setOpen(false)} style={{ fontSize: 11, marginTop: 10 }}>閉じる</button>
        </div>
      )}
    </span>
  );
}

function StateChip({ t }) {
  if (!t.label) return <div style={{ fontSize: 11.5, color: P.muted, fontWeight: 600 }}>{t.note}</div>;
  return (
    <>
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '6px 13px', borderRadius: 20, background: '#fff', border: `1px solid ${t.line}` }}>
        <span style={{ width: 7, height: 7, borderRadius: 7, background: t.fg }}></span>
        <span style={{ fontSize: 12.5, fontWeight: 800, color: t.fg, letterSpacing: '.01em', whiteSpace: 'nowrap' }}>{t.label}</span>
      </span>
      <div style={{ fontSize: 11.5, color: P.muted, marginTop: 8, lineHeight: 1.65, fontWeight: 600 }}>{t.note}</div>
    </>
  );
}

function Sec8({ label, right, children, t }) {
  return (
    <div style={{ padding: '17px 22px 18px', borderTop: `1px solid ${P.line}` }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, marginBottom: 10 }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 10.5, fontWeight: 800, color: P.faint, letterSpacing: '.12em', whiteSpace: 'nowrap' }}>{label}</span>
        {right}
      </div>
      {children}
    </div>
  );
}

// 左固定カード：対象者・注意度・総合スコア（前回比＋簡易推移）・今回1on1
function Rail8({ state = 'attn', rounds = R8.rounds, score = R8.score, delta = R8.delta, done = null, daysAgo = 39, id = 'r8', compact = false, name = 'B班 副班長L' }) {
  const t = S8[state];
  const nodata = state === 'nodata';
  return (
    <div style={{ background: '#fff', borderRadius: 16, border: `1px solid ${P.line}`, boxShadow: '0 1px 2px rgba(18,22,30,.05), 0 14px 32px -20px rgba(18,22,30,.2)', overflow: 'hidden', width: 296, flexShrink: 0 }}>
      <div style={{ padding: compact ? '20px 22px 16px' : '24px 22px 18px', textAlign: 'center', background: t.head }}>
        <div style={{ display: 'flex', justifyContent: 'center' }}><Face size={compact ? 54 : 62} /></div>
        <div style={{ fontSize: 18.5, fontWeight: 800, color: P.ink, marginTop: 11 }}>{name}</div>
        <div style={{ fontSize: 12, color: P.muted, marginTop: 5 }}>2部 ・ L / 副班長<br />勤続 3年11ヶ月</div>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginTop: 7 }}>
          <span style={{ fontSize: 11, color: P.faint }}>担当者</span>
          <span style={{ fontSize: 12, fontWeight: 700, color: P.ink2 }}>B班 班長</span>
          <button className="quiet" aria-label="担当者を編集" style={{ width: 22, height: 22, borderRadius: 7, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', padding: 0, background: 'rgba(255,255,255,.7)' }}>
            <svg width="11" height="11" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M11.3 2.2l2.5 2.5L5.5 13H3v-2.5l8.3-8.3z"></path></svg>
          </button>
        </div>
      </div>

      <Sec8 t={t} label={<>総合スコア <ScoreHelp /></>}>
        {nodata ? (
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 9 }}>
            <span className="tnum" style={{ fontSize: 34, fontWeight: 800, lineHeight: 1, color: P.ghost }}>—</span>
            <span style={{ fontSize: 12, fontWeight: 700, color: P.muted }}>今回は未回答</span>
          </div>
        ) : (
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 10 }}>
            <span style={{ display: 'flex', alignItems: 'baseline', gap: 5 }}>
              <span className="tnum" style={{ fontSize: 40, fontWeight: 800, lineHeight: 1, color: P.ink, letterSpacing: '-.01em' }}>{score.toFixed(1)}</span>
              <span className="tnum" style={{ fontSize: 12, fontWeight: 600, color: P.ghost }}>/ 5.0</span>
            </span>
            <span style={{ display: 'inline-flex', alignItems: 'baseline', gap: 5, whiteSpace: 'nowrap' }}>
              <span style={{ fontSize: 10.5, fontWeight: 700, color: P.faint }}>前回比</span>
              {delta === 0 ? (
                <span className="tnum" style={{ fontSize: 17, fontWeight: 800, color: P.ghost, letterSpacing: '-.01em' }}>±0</span>
              ) : (
                <>
                  <span className="tnum" style={{ fontSize: 17, fontWeight: 800, color: delta > 0 ? P.up : P.down, letterSpacing: '-.01em' }}>{delta > 0 ? '+' : '−'}{Math.abs(delta)}</span>
                  <span className="tnum" style={{ fontSize: 12, fontWeight: 800, color: delta > 0 ? P.up : P.down }}>{delta > 0 ? '↑' : '↓'}</span>
                </>
              )}
            </span>
          </div>
        )}
        <div style={{ marginTop: 5, background: '#fff', borderRadius: 11, padding: '8px 2px 4px' }}>
          <MiniTrend rounds={rounds} w={244} h={compact ? 68 : 76} id={id} />
        </div>
      </Sec8>

      <Sec8 t={t} label="今回1on1">
        {done ? (
          <>
            <div className="tnum" style={{ fontSize: 17, fontWeight: 800, color: P.ink }}>{done.date} 実施</div>
            <div style={{ fontSize: 11.5, fontWeight: 600, color: P.muted, marginTop: 5 }}>{done.method}</div>
          </>
        ) : (
          <>
            <div style={{ fontSize: 17, fontWeight: 800, color: P.down }}>未実施</div>
            <div className="tnum" style={{ fontSize: 11.5, fontWeight: 600, color: P.muted, marginTop: 5 }}>前回 2026/05/15（{daysAgo}日前）</div>
          </>
        )}
      </Sec8>

      <div style={{ padding: '16px 22px 20px', borderTop: `1px solid ${P.line}`, display: 'flex', flexDirection: 'column', gap: 9 }}>
        <button className="rec-btn" style={{ padding: '12px 0', fontSize: 13.5, width: '100%' }}>
          <svg width="15" height="15" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M11.5 2.5l2 2L5 13l-2.7.7.7-2.7z" strokeLinecap="round" strokeLinejoin="round" /></svg>
          {done ? '実施記録を編集' : '実施記録を登録'}
        </button>
        <button className="quiet" style={{ padding: '10px 0', fontSize: 12.5, width: '100%' }}>プロフィール詳細</button>
      </div>
    </div>
  );
}

Object.assign(window, { V8: { S8, R8, ROUNDS_OK, ROUNDS_BAD, ROUNDS_NODATA, MiniTrend, Rail8, Sec8, NEU } });
