// bu/v8.jsx — AI補助あり版：アンケート詳細 ＋ 画面（実施前 / 実施後）＋ 注意喚起の状態差
const { AppFrame, PageBar } = window;
const { P, Q, DeltaChip } = window.V4;
const { CardB, HeadB, ThreadBody, LTH } = window.V7;
const { Rail8, R8, ROUNDS_OK, ROUNDS_BAD, ROUNDS_NODATA, NEU } = window.V8;
const { CheckCard8, AiCard8, RecordCardBefore, RecordCardAfter, DONE8 } = window;

// 設問ごとの推移（3月は未回答＝つながない）
const hist6 = (h) => [h[0], h[1], null, h[2], h[3], h[4]];

// 設問行の小推移：縦軸1〜5固定・未回答は破線
function RowSpark({ data, color, w = 78, h = 24, id }) {
  const pad = 3;
  const yv = (v) => (h - pad) - ((v - 1) / 4) * (h - 2 * pad);
  const xs = data.map((_, i) => pad + (i / (data.length - 1)) * (w - 2 * pad));
  const segs = []; let run = [];
  data.forEach((v, i) => { if (v != null) run.push(i); else { if (run.length) segs.push(run); run = []; } });
  if (run.length) segs.push(run);
  const ans = data.map((v, i) => (v != null ? i : -1)).filter((i) => i >= 0);
  const last = ans[ans.length - 1];
  return (
    <svg width={w} height={h} viewBox={`0 0 ${w} ${h}`} style={{ display: 'block', overflow: 'visible' }} aria-hidden="true">
      <line x1="0" x2={w} y1={yv(1)} y2={yv(1)} stroke="#f0f2f5" strokeWidth="1" />
      <line x1="0" x2={w} y1={yv(5)} y2={yv(5)} stroke="#f0f2f5" strokeWidth="1" />
      {segs.map((s, k) => {
        const nx = segs[k + 1]; if (!nx) return null;
        const a = s[s.length - 1], b = nx[0];
        return <line key={`g${k}`} x1={xs[a]} y1={yv(data[a])} x2={xs[b]} y2={yv(data[b])} stroke="#cdd2d9" strokeWidth="1.2" strokeDasharray="2 3" />;
      })}
      {segs.map((s, k) => s.length < 2 ? null : (
        <polyline key={k} points={s.map((i) => `${xs[i].toFixed(1)},${yv(data[i]).toFixed(1)}`).join(' ')} fill="none" stroke={color} strokeWidth="1.7" strokeLinejoin="round" strokeLinecap="round" />
      ))}
      {last != null && <circle cx={xs[last]} cy={yv(data[last])} r="2.8" fill={color} />}
    </svg>
  );
}

// 回答状況の帯：正確な回答日・未回答の期限超過・期限後回答の遅延
function AnswerStrip() {
  return (
    <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 18 }}>
      {R8.rounds.map((r, i) => (
        <div key={i} style={{
          display: 'flex', flexDirection: 'column', gap: 3, padding: '8px 12px 9px', borderRadius: 10, minWidth: 92,
          background: r.missing ? '#f6f7f8' : '#fff', border: r.missing ? '1px dashed #d5d9df' : `1px solid ${P.line}`,
        }}>
          <span className="tnum" style={{ fontSize: 10.5, fontWeight: 800, color: r.missing ? P.faint : P.muted, letterSpacing: '.04em' }}>{r.m}</span>
          {r.missing ? (
            <>
              <span style={{ fontSize: 12, fontWeight: 800, color: P.muted }}>未回答</span>
              <span className="tnum" style={{ fontSize: 10, color: P.faint }}>期限 {r.deadline.slice(5)} 超過</span>
            </>
          ) : (
            <>
              <span className="tnum" style={{ fontSize: 12.5, fontWeight: 800, color: P.ink }}>{r.date.slice(5)}</span>
              <span className="tnum" style={{ fontSize: 10, color: r.late ? '#8a6b12' : P.ghost }}>{r.late ? `期限後 ${r.late}日遅れ` : '期限内'}</span>
            </>
          )}
        </div>
      ))}
    </div>
  );
}

function SurveyRow8({ s, last, idx }) {
  const delta = s.cur - s.prev;
  const changed = delta !== 0;
  const c = delta < 0 ? P.down : delta > 0 ? P.up : P.ghost;
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 86px 92px 58px', gap: 16, alignItems: 'center', padding: '13px 0', borderBottom: last ? 'none' : `1px solid ${P.lineSoft}` }}>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 13.5, fontWeight: changed ? 700 : 600, color: P.ink }}>{s.q}</div>
        <div style={{ fontSize: 11, color: P.ghost, marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.desc}</div>
      </div>
      <span style={{ display: 'flex', justifyContent: 'center' }}><RowSpark data={hist6(s.hist)} color={changed ? c : NEU} id={`v8sv${idx}`} /></span>
      <span style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'flex-end', gap: 7 }}>
        <span className="tnum" style={{ fontSize: 12, color: P.ghost }}>{s.prev}</span>
        <span style={{ color: P.ghost, fontSize: 11 }}>→</span>
        <span className="tnum" style={{ fontSize: 16, fontWeight: 800, color: changed ? P.ink : P.muted }}>{s.cur}</span>
      </span>
      <span style={{ display: 'flex', justifyContent: 'flex-end' }}><DeltaChip delta={delta} /></span>
    </div>
  );
}

// アンケート詳細：どの設問が、いつ、どのように変化したかを確認する場所
function SurveyCard8({ nodata = false }) {
  const [open, setOpen] = React.useState(false);
  const changed = Q.survey.filter((s) => s.cur !== s.prev);
  const flat = Q.survey.filter((s) => s.cur === s.prev);
  const nDown = Q.survey.filter((s) => s.cur < s.prev).length;
  const bc = nDown > 0 ? { fg: P.down, bg: 'rgba(214,66,89,.09)', ln: 'rgba(214,66,89,.28)' } : { fg: P.up, bg: 'rgba(31,146,90,.09)', ln: 'rgba(31,146,90,.28)' };
  return (
    <CardB pad={open ? '24px 30px 26px' : '20px 30px'}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, marginBottom: open ? 16 : 0 }}>
        <button onClick={() => setOpen((v) => !v)} aria-expanded={open} style={{ all: 'unset', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 10, flex: 1, minWidth: 0 }}>
          <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke={P.faint} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ transform: open ? 'rotate(90deg)' : 'none', transition: 'transform .18s ease', flexShrink: 0 }}><path d="M6 4l4 4-4 4" /></svg>
          <span className="lbl8" style={{ fontSize: 12.5, fontWeight: 700, color: P.faint, letterSpacing: '.12em' }}>アンケート詳細</span>
          {!open && (nodata ? (
            <span className="lbl8" style={{ fontSize: 11.5, fontWeight: 700, color: P.muted, background: P.inset, border: `1px solid ${P.line}`, borderRadius: 20, padding: '3px 11px' }}>今回未回答 ・ 前回までの回答を表示</span>
          ) : (
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '3px 10px', borderRadius: 20, background: bc.bg, border: `1px solid ${bc.ln}` }}>
              <span style={{ width: 6, height: 6, borderRadius: 6, background: bc.fg }}></span>
              <span className="lbl8" style={{ fontSize: 11.5, fontWeight: 800, color: bc.fg }}>変化あり <span className="tnum">{changed.length}</span>件</span>
            </span>
          ))}
        </button>
        {open && <button className="tlnk" style={{ fontSize: 12, flexShrink: 0 }}>過去回答一覧</button>}
      </div>
      {open && (
        <>
          <div style={{ fontSize: 11, fontWeight: 800, color: P.faint, letterSpacing: '.1em', marginBottom: 9 }}>回答状況（直近6回）</div>
          <AnswerStrip />
          <div style={{ fontSize: 11.5, fontWeight: 700, color: P.muted, marginBottom: 2 }}>変化あり <span className="tnum" style={{ color: P.ghost, fontWeight: 600 }}>{changed.length}</span></div>
          {changed.map((s, i) => <SurveyRow8 key={i} s={s} idx={i} last={i === changed.length - 1} />)}
          <details style={{ marginTop: 16 }}>
            <summary className="tlnk" style={{ fontSize: 12, display: 'inline-block' }}>変化なし {flat.length}件を表示</summary>
            <div style={{ marginTop: 6 }}>
              {flat.map((s, i) => <SurveyRow8 key={i} s={s} idx={`f${i}`} last={i === flat.length - 1} />)}
            </div>
          </details>
        </>
      )}
    </CardB>
  );
}

function ThreadCard8() {
  return <CardB pad="24px 30px 30px"><HeadB><span className="lbl8">コメント</span></HeadB><ThreadBody th={LTH} inputCls="fin" actCls="act" /></CardB>;
}

// ═ 1on1 実施前 ═
function ScreenV8Before() {
  return (
    <div className="v4">
      <AppFrame>
        <PageBar plainLabel="6月度 月次1on1アンケート" />
        <div style={{ display: 'grid', gridTemplateColumns: '296px 1fr', gap: 16, alignItems: 'start' }}>
          <Rail8 state="attn" id="b4" />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 22, minWidth: 0 }}>
            <CheckCard8 idx="bf" ai />
            <SurveyCard8 />
            <RecordCardBefore />
            <ThreadCard8 />
          </div>
        </div>
      </AppFrame>
    </div>
  );
}

// ═ 1on1 実施後 ═
function ScreenV8After() {
  return (
    <div className="v4">
      <AppFrame>
        <PageBar plainLabel="6月度 月次1on1アンケート" />
        <div style={{ display: 'grid', gridTemplateColumns: '296px 1fr', gap: 16, alignItems: 'start' }}>
          <Rail8 state="attn" id="af" done={{ date: DONE8.date, method: DONE8.method }} />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 22, minWidth: 0 }}>
            <RecordCardAfter />
            <CheckCard8 after idx="af" ai />
            <SurveyCard8 />
            <ThreadCard8 />
          </div>
        </div>
      </AppFrame>
    </div>
  );
}

// ═ 注意喚起の状態差（左カード＋確認ポイント上部の縮小比較） ═
const ST_CASES = [
  {
    key: 'plain', title: '通常（青系・ラベルなし）', desc: '黄・赤に該当する追加の注意喚起がない状態。断定的な「良好」ラベルは付けない。',
    rail: { state: 'plain', rounds: ROUNDS_OK, score: 4.2, delta: 0.3, id: 'sp' },
    rows: [{ kind: 'survey', q: 'やりがい', prev: 4, cur: 5, hist: [4, 4, 4, 4, 5], reason: '上昇' }],
  },
  {
    key: 'attn', title: '確認ポイントあり（黄系・注意喚起ラベル）', desc: '今回、意識して確認してほしい項目がある。ラベル＋説明文を併記し、色だけに意味を持たせない。',
    rail: { state: 'attn', rounds: R8.rounds, score: 3.9, delta: 0.1, id: 'sa' },
    rows: Q.checkpoints.slice(0, 3),
  },
  {
    key: 'follow', title: '要フォロー（赤系・注意喚起ラベル）', desc: 'しっかりフォローしてほしい内容がある。フォロー対応済みかどうかは別軸で、対応済みでも赤は解除しない。',
    rail: { state: 'follow', rounds: ROUNDS_BAD, score: 2.4, delta: -0.8, id: 'sf' },
    rows: [
      { kind: 'survey', q: '仕事内容満足度', prev: 3, cur: 1, hist: [4, 4, 3, 3, 1], reason: '大きく低下' },
      { kind: 'survey', q: 'モチベーション', prev: 3, cur: 2, hist: [3, 3, 3, 3, 2], reason: '低下' },
      { kind: 'signal', q: '前回1on1から1か月以上経過（39日）', reason: '1on1未実施期間' },
    ],
  },
  {
    key: 'nodata', title: 'データ不足（グレー系）', desc: '今回のアンケートが未回答。通常状態と混同させず、スコアは「—」、確認ポイントは事実のみ。',
    rail: { state: 'nodata', rounds: ROUNDS_NODATA, id: 'sn' },
    nodata: true,
  },
];

function MiniCheck({ c }) {
  return (
    <div style={{ flex: 1, minWidth: 0, position: 'relative', marginTop: 22 }}>
      <div style={{ position: 'absolute', top: -22, left: 0, right: 0, display: 'flex', justifyContent: 'center', pointerEvents: 'none' }}>
        <window.TabCheck8 title="今回の確認ポイント" state={c.rail.state} n={c.nodata ? 0 : c.rows.length} nodata={c.nodata} />
      </div>
      <div style={{ background: '#fff', borderRadius: 14, border: `1.5px solid #dcdfe5`, boxShadow: '0 1px 2px rgba(18,22,30,.04)', padding: '40px 24px 18px', height: '100%', boxSizing: 'border-box' }}>
      {c.nodata ? (
        <div style={{ background: P.inset, border: '1px dashed #d9dde3', borderRadius: 11, padding: '15px 17px' }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: P.ink2, lineHeight: 1.65 }}>確認ポイントはアンケート回答後に表示されます</div>
          <div className="tnum" style={{ fontSize: 12, color: P.muted, marginTop: 9, lineHeight: 1.8, fontWeight: 600 }}>未回答（期限 2026/06/25 を 3日超過）<br />前回1on1 2026/05/15（39日前）</div>
        </div>
      ) : (
        <>
          <div style={{ marginTop: -6 }}>
            {c.rows.map((r, i) => <window.CheckRow8 key={i} item={r} idx={`${c.key}${i}`} last={i === c.rows.length - 1} />)}
          </div>
          {c.empty && <div style={{ fontSize: 11.5, color: P.muted, marginTop: 12, lineHeight: 1.7 }}>{c.empty}</div>}
        </>
      )}
      <div style={{ marginTop: 14, paddingTop: 13, borderTop: `1px solid ${P.line}`, fontSize: 11, color: P.ghost, lineHeight: 1.7 }}>
        {c.nodata ? 'AIからの提案：根拠不足のため非表示（理由文のみ）' : 'この下に 本人コメント → AIからの提案 → 詳細情報 が続く'}
      </div>
      </div>
    </div>
  );
}

function StatePanel8() {
  return (
    <div className="v4" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 26 }}>
      {ST_CASES.map((c) => (
        <div key={c.key} style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
          <div style={{ padding: '0 2px' }}>
            <div style={{ fontSize: 13.5, fontWeight: 800, color: window.V8.S8[c.rail.state].fg }}>{c.title}</div>
            <div style={{ fontSize: 11.5, color: P.muted, marginTop: 4, lineHeight: 1.65, maxWidth: 620 }}>{c.desc}</div>
          </div>
          <div style={{ display: 'flex', gap: 16, alignItems: 'stretch' }}>
            <Rail8 {...c.rail} compact />
            <MiniCheck c={c} />
          </div>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { ScreenV8Before, ScreenV8After, StatePanel8, SurveyCard8, RowSpark });
