// bu/v7a2.jsx — 案B スプリットビューのブラッシュアップ版
//  確認ポイントは案Bの縦並び行構造のまま、行頭に色付きアイコンチップを追加して
//  キャプチャの色味に寄せる（低下=ローズ/上昇=グリーン/経過日数=ブルー/日報=バイオレット）。collab連携ラベルは非表示。
const { AppFrame, PageBar, Face, Icon } = window;
const { P, Q, AreaSpark, ScoreRing, DeltaChip } = window.V4;
const { CardB, HeadB, RailSec, CommentBody, RecordBody, SurveyBody, ThreadBody, LTH } = window.V7;

// キャプチャ寄せの鮮やかトーン
const C2 = {
  down: '#e5495f', downBg: '#fdedf0',
  up: '#17a05e', upBg: '#e9f7f0',
  warn: '#c1860c', warnBg: '#fdf3d9',
  sig: '#3b7ce0', sigBg: '#e9f1fd',
  doc: '#8f6fe8', docBg: '#f1edfd',
};

// 本文テキスト（3行程度の分量・折りたたみなしで全文表示）
const TXT2 = {
  comment: '6月は案件の切り替えがあり、前半はキャッチアップに時間がかかりました。後半は落ち着いてきましたが、新しいチームでの進め方にまだ慣れていない部分があります。次の目標について、資格学習の時間の確保も含めて相談したいです。',
  commentPrev: '5月は特に大きな課題はありません。次の目標について相談したいです。',
  report: '5月の1on1で目標進捗と困りごとをヒアリング。案件切り替えに伴う引き継ぎ状況を確認し、負荷が高い期間が続いていたためタスクの優先順位を一緒に整理した。次回までの小さな改善アクション（朝会での相談枠の活用）を合意。',
  memo: '表情はやや疲れ気味。次回は資格学習の話題を先にこちらから振る。',
};

// 本人コメント：カード下部の灰色帯＋白の吹き出し
function CommentBand2({ th, radius = 13 }) {
  return (
    <div style={{ margin: '4px -30px -20px', padding: '18px 30px 22px', background: P.inset, borderTop: `1px solid ${P.line}`, borderRadius: `0 0 ${radius}px ${radius}px` }}>
      <div style={{ fontSize: 11.5, fontWeight: 700, color: P.faint, letterSpacing: '.08em', marginBottom: 12 }}>本人コメント</div>
      <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
        <Face size={38} />
        <div style={{ flex: 1, minWidth: 0, position: 'relative', background: '#fff', border: `1px solid ${P.line}`, borderRadius: '4px 14px 14px 14px', padding: '16px 20px 16px 22px' }}>
          <span aria-hidden="true" style={{ position: 'absolute', top: 4, left: 8, fontFamily: 'Georgia, serif', fontSize: 30, lineHeight: 1, color: th.ghost, opacity: .55 }}>“</span>
          <p style={{ margin: 0, fontSize: 15, lineHeight: 1.9, color: th.ink, letterSpacing: '.01em' }}>{TXT2.comment}</p>
        </div>
      </div>
      <details style={{ marginTop: 14, marginLeft: 52 }}>
        <summary className="tlnk" style={{ fontSize: 12, display: 'inline-block' }}>前回のコメントを見る</summary>
        <p style={{ margin: '10px 0 0', fontSize: 12.5, lineHeight: 1.8, color: th.muted, paddingLeft: 14, borderLeft: `2px solid ${th.line}` }}>{TXT2.commentPrev}</p>
      </details>
    </div>
  );
}

// 前回1on1記録：開閉式カード（見出しクリックで本文を開閉）
function RecordCard2({ th }) {
  const [open, setOpen] = React.useState(false);
  return (
    <CardB pad={open ? '24px 30px 26px' : '20px 30px'}>
      <button
        onClick={() => setOpen((v) => !v)}
        aria-expanded={open}
        style={{ all: 'unset', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, width: '100%', marginBottom: open ? 16 : 0 }}
      >
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 10 }}>
          <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 style={{ fontSize: 12.5, fontWeight: 700, color: P.faint, letterSpacing: '.12em' }}>前回1on1記録</span>
        </span>
        <span className="tnum" style={{ fontSize: 12, color: P.ghost }}>{Q.record.date} ・ {Q.record.method}</span>
      </button>
      {open && <RecordBody2 th={th} />}
    </CardB>
  );
}

// アンケート詳細：開閉式カード（閉じている間は「変化あり」件数を色付きで表示）
function SurveyCard2({ th }) {
  const [open, setOpen] = React.useState(false);
  const nChanged = Q.survey.filter((s) => s.cur !== s.prev).length;
  const nDown = Q.survey.filter((s) => s.cur < s.prev).length;
  const badgeC = nDown > 0 ? { fg: P.down, bg: 'rgba(214,66,89,.09)', line: 'rgba(214,66,89,.28)' } : { fg: P.up, bg: 'rgba(31,146,90,.09)', line: '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 style={{ fontSize: 12.5, fontWeight: 700, color: P.faint, letterSpacing: '.12em' }}>アンケート詳細</span>
          {!open && nChanged > 0 && (
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '3px 10px', borderRadius: 20, background: badgeC.bg, border: `1px solid ${badgeC.line}` }}>
              <span style={{ width: 6, height: 6, borderRadius: 6, background: badgeC.fg }}></span>
              <span style={{ fontSize: 11.5, fontWeight: 800, color: badgeC.fg }}>変化あり <span className="tnum">{nChanged}</span>件</span>
            </span>
          )}
        </button>
        {open && <button className="tlnk" style={{ fontSize: 12, flexShrink: 0 }}>過去回答一覧</button>}
      </div>
      {open && <SurveyBody th={th} prefix="v7a2" linkCls="tlnk" />}
    </CardB>
  );
}

// 前回1on1記録：本文全文＋自分用メモはフッター扱い
function RecordBody2({ th }) {
  return (
    <>
      <p style={{ margin: 0, fontSize: 14, lineHeight: 1.85, color: th.ink2 }}>{TXT2.report}</p>
      <div style={{ marginTop: 16, background: '#fdf6de', border: '1px solid #efe3b5', borderRadius: 10, padding: '13px 18px 14px' }}>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11, fontWeight: 700, color: '#9a814a', marginBottom: 6 }}>
          <Icon.lock width="12" height="12" /> 自分用メモ
        </div>
        <p style={{ margin: 0, fontSize: 12.5, lineHeight: 1.75, color: '#6b5c3a' }}>{TXT2.memo}</p>
      </div>
    </>
  );
}

// 行頭の色付きアイコンチップ
function IconChip2({ tone, bg, children }) {
  return (
    <span style={{ width: 30, height: 30, borderRadius: 9, background: bg, color: tone, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{children}</span>
  );
}
const ChipIcons = {
  trendDown: <svg width="16" height="16" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 6l5 5 3-3 6 6" /><path d="M17 10v4h-4" /></svg>,
  trendUp: <svg width="16" height="16" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 14l5-5 3 3 6-6" /><path d="M17 10V6h-4" /></svg>,
  calendar: <svg width="16" height="16" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round"><rect x="3" y="4.5" width="14" height="12.5" rx="2" /><path d="M3 8.5h14M7 2.8v3M13 2.8v3" /></svg>,
  doc: <svg width="16" height="16" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M5 2.8h7l3.5 3.5v10.9H5z" /><path d="M12 2.8v3.5h3.5M7.6 10h4.8M7.6 13h4.8" /></svg>,
};

// 確認ポイント行：案Bの縦並び行構造＋色付きアイコンチップ
function CheckRowCap({ item, idx, last }) {
  const border = last ? 'none' : `1px solid ${P.line}`;
  if (item.kind === 'signal') {
    const isDays = item.reason.includes('未実施');
    // ネガティブ=赤 / ポジティブ=緑（意味で判定）
    const positive = /上昇|改善|向上|回復/.test(item.reason);
    const tone = positive ? C2.up : C2.down;
    const bg = positive ? C2.upBg : C2.downBg;
    // 未実施アラートの“語り”はここに一本化（レール側は事実のみ）
    const label = isDays ? `前回1on1から1か月以上経過（${Q.last.daysAgo}日）` : item.q;
    const note = isDays ? '1on1未実施期間' : item.reason;
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '13px 0', borderBottom: border }}>
        <IconChip2 tone={tone} bg={bg}>{isDays ? ChipIcons.calendar : ChipIcons.doc}</IconChip2>
        <span style={{ flex: 1, minWidth: 0, fontSize: 14.5, fontWeight: 700, color: P.ink }}>{label}</span>
        <span className="tnum" style={{ fontSize: 11.5, fontWeight: 700, color: tone, letterSpacing: '.03em', whiteSpace: 'nowrap' }}>{note}</span>
      </div>
    );
  }
  const delta = item.cur - item.prev;
  const tone = delta < 0 ? C2.down : C2.up;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '13px 0', borderBottom: border }}>
      <IconChip2 tone={tone} bg={delta < 0 ? C2.downBg : C2.upBg}>{delta < 0 ? ChipIcons.trendDown : ChipIcons.trendUp}</IconChip2>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 15.5, fontWeight: 800, color: P.ink, letterSpacing: '.01em' }}>{item.q}</div>
        <div style={{ fontSize: 11.5, fontWeight: 700, color: tone, letterSpacing: '.03em', marginTop: 4 }}>{item.reason}</div>
      </div>
      <AreaSpark data={item.hist} color={tone} w={84} h={30} id={`v7a2cp${idx}`} />
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, width: 106, justifyContent: 'flex-end' }}>
        <span className="tnum" style={{ fontSize: 14, color: P.faint, fontWeight: 600 }}>{item.prev}</span>
        <span style={{ color: P.faint, fontSize: 12 }}>→</span>
        <span className="tnum" style={{ fontSize: 27, fontWeight: 800, lineHeight: 1, color: tone }}>{item.cur}</span>
      </div>
      <div style={{ width: 56, display: 'flex', justifyContent: 'flex-end' }}><DeltaChip delta={delta} /></div>
    </div>
  );
}

// 総合スコアの部署／班平均との比較（本人スコアとの差分を控えめに併記）
function AvgCompareRail({ score, deptAvg, teamAvg }) {
  const rows = [
    { label: '2部 平均', avg: deptAvg },
    { label: 'B班 平均', avg: teamAvg },
  ];
  return (
    <div style={{ marginTop: 16, paddingTop: 14, borderTop: `1px solid ${P.line}`, display: 'flex', flexDirection: 'column', gap: 9 }}>
      {rows.map((r, i) => {
        const diff = Math.round((score - r.avg) * 10) / 10;
        const up = diff > 0, flat = diff === 0;
        const tone = flat ? P.faint : up ? P.up : P.down;
        return (
          <div key={i} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
            <span style={{ fontSize: 12, fontWeight: 600, color: P.muted }}>{r.label}</span>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
              <span className="tnum" style={{ fontSize: 15, fontWeight: 700, color: P.ink2 }}>{r.avg.toFixed(1)}</span>
              <span className="tnum" style={{ fontSize: 11, fontWeight: 800, color: tone, minWidth: 42, textAlign: 'right' }}>
                {flat ? '±0.0' : `${up ? '+' : '−'}${Math.abs(diff).toFixed(1)}`}
              </span>
            </div>
          </div>
        );
      })}
    </div>
  );
}

function ScreenV7A2() {
  const th = LTH;
  return (
    <div className="v4">
      <AppFrame>
        <PageBar plainLabel="6月度 月次1on1アンケート" />
        <div style={{ display: 'grid', gridTemplateColumns: '296px 1fr', gap: 16, alignItems: 'start' }}>

          {/* ═ 判断レール（左固定・案Bと同一） ═ */}
          <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' }}>
            <div style={{ padding: '26px 24px 20px', textAlign: 'center', background: 'linear-gradient(180deg,#faf4e3 0%,#fff 90%)' }}>
              <div style={{ display: 'flex', justifyContent: 'center' }}><Face size={64} /></div>
              <div style={{ fontSize: 19, fontWeight: 800, color: P.ink, marginTop: 12 }}>{Q.member.name}</div>
              <div style={{ fontSize: 12, color: P.muted, marginTop: 5 }}>{Q.member.dept} ・ {Q.member.role}<br />勤続 {Q.member.tenure}</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 }}>
                  <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>
            <RailSec label={<span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>総合スコア <DeltaChip delta={Q.summary.delta} /></span>}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 20 }}>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
                  <span className="tnum" style={{ fontSize: 42, fontWeight: 800, lineHeight: 1, color: P.ink, letterSpacing: '-.01em' }}>{Q.summary.score}</span>
                  <span className="tnum" style={{ fontSize: 12, fontWeight: 600, color: P.ghost }}>/ 5.0</span>
                </div>
                <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', alignItems: 'flex-end' }}>
                  <AreaSpark data={Q.summary.trend} color={Q.summary.delta > 0 ? P.up : Q.summary.delta < 0 ? P.down : '#2a6fdb'} w={120} h={30} id="v7a2rail" />
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 3, width: 120 }}>
                    <span className="tnum" style={{ fontSize: 10, color: P.ghost }}>2月</span>
                    <span className="tnum" style={{ fontSize: 10, color: P.ghost }}>6月</span>
                  </div>
                </div>
              </div>
            </RailSec>
            <RailSec label="今回1on1">
              <div style={{ fontSize: 17, fontWeight: 800, color: P.down }}>未実施</div>
              <div className="tnum" style={{ fontSize: 11.5, fontWeight: 600, color: P.muted, marginTop: 5 }}>前回 {Q.last.date}（{Q.last.daysAgo}日前）</div>
            </RailSec>
            <div style={{ padding: '18px 24px 22px', borderTop: `1px solid ${P.line}`, display: 'flex', flexDirection: 'column', gap: 9 }}>
              <button className="act" style={{ padding: '12px 0', fontSize: 13.5, width: '100%' }}>実施記録を登録</button>
              <button className="quiet" style={{ padding: '10px 0', fontSize: 12.5, width: '100%' }}>プロフィール詳細</button>
            </div>
          </div>

          {/* ═ 根拠フロー（右） ═ */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14, minWidth: 0 }}>
            <CardB hero pad="24px 30px 20px">
              <HeadB right={<span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '5px 12px', borderRadius: 20, background: P.warnBg, border: `1px solid ${P.warnLine}` }}><span style={{ width: 7, height: 7, borderRadius: 7, background: P.warn }}></span><span style={{ fontSize: 12, fontWeight: 800, color: P.ink }}>やや注意</span></span>}>今回の確認ポイント</HeadB>
              <div style={{ marginTop: -4 }}>
                {Q.checkpoints.filter((c) => c.src !== 'collab').map((c, i, arr) => <CheckRowCap key={i} item={c} idx={i} last={i === arr.length - 1} />)}
              </div>
              <CommentBand2 th={th} />
            </CardB>
            <SurveyCard2 th={th} />
            <RecordCard2 th={th} />
            <CardB pad="24px 30px 30px"><HeadB>コメント</HeadB><ThreadBody th={th} inputCls="fin" actCls="act" /></CardB>
          </div>
        </div>
      </AppFrame>
    </div>
  );
}

// ═ 確認ポイント例（実際の表示デザインのままモックした例）═
const EX_WARN = { fg: '#c08a12', bg: '#fdf4dc', line: '#efe0b0' };
const EX_NEG = { fg: C2.down, bg: C2.downBg, line: '#f5cdd5' };
const ExIcons = {
  clock: <svg width="16" height="16" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><circle cx="10" cy="10" r="7.2" /><path d="M10 5.8V10l3 2" /></svg>,
  repeat: <svg width="16" height="16" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M4 8a6 6 0 0 1 10.5-2.5M16 12a6 6 0 0 1-10.5 2.5" /><path d="M14.5 2.5v3h-3M5.5 17.5v-3h3" /></svg>,
};
function ExChip({ t, children }) {
  return <span className="tnum" style={{ fontSize: 11.5, fontWeight: 800, color: t.fg, background: t.bg, border: `1px solid ${t.line}`, borderRadius: 999, padding: '3px 10px', whiteSpace: 'nowrap' }}>{children}</span>;
}
// シグナル型の例行（CheckRowCapのsignal行と同じ造り）
function ExSignalRow({ t, icon, label, note, last }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '13px 0', borderBottom: last ? 'none' : `1px solid ${P.line}` }}>
      <IconChip2 tone={t.fg} bg={t.bg}>{icon}</IconChip2>
      <span style={{ flex: 1, minWidth: 0, fontSize: 14.5, fontWeight: 700, color: P.ink }}>{label}</span>
      <span className="tnum" style={{ fontSize: 11.5, fontWeight: 700, color: t.fg, letterSpacing: '.03em', whiteSpace: 'nowrap' }}>{note}</span>
    </div>
  );
}
// アンケート型の例行（CheckRowCapのsurvey行と同じ造り、トーンは固定指定）
function ExSurveyRow({ t, q, reason, prev, cur, hist, id, last }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '13px 0', borderBottom: last ? 'none' : `1px solid ${P.line}` }}>
      <IconChip2 tone={t.fg} bg={t.bg}>{ChipIcons.trendDown}</IconChip2>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 15.5, fontWeight: 800, color: P.ink, letterSpacing: '.01em' }}>{q}</div>
        <div style={{ fontSize: 11.5, fontWeight: 700, color: t.fg, letterSpacing: '.03em', marginTop: 4 }}>{reason}</div>
      </div>
      <AreaSpark data={hist} color={t.fg} w={84} h={30} id={id} />
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, width: 76, justifyContent: 'flex-end' }}>
        <span className="tnum" style={{ fontSize: 14, color: P.faint, fontWeight: 600 }}>{prev}</span>
        <span style={{ color: P.faint, fontSize: 12 }}>→</span>
        <span className="tnum" style={{ fontSize: 27, fontWeight: 800, lineHeight: 1, color: t.fg }}>{cur}</span>
      </div>
      <div style={{ width: 56, display: 'flex', justifyContent: 'flex-end' }}><ExChip t={t}>{cur - prev > 0 ? `+${cur - prev}` : cur - prev}</ExChip></div>
    </div>
  );
}
function CheckExamplesPanel() {
  return (
    <div className="v4" style={{ width: '100%', background: '#fff', borderRadius: 16, border: `1px solid ${P.line}`, boxShadow: '0 1px 2px rgba(18,22,30,.05)', padding: '22px 30px 24px' }}>
      <div style={{ fontSize: 14.5, fontWeight: 800, color: P.ink, letterSpacing: '.02em' }}>確認ポイント例</div>
      <div style={{ fontSize: 12, color: P.muted, marginTop: 5, lineHeight: 1.7 }}>自動抽出されたときの実際の表示イメージ。赤＝ネガティブ／黄＝やや注意。</div>
      <div style={{ marginTop: 8 }}>
        <ExSignalRow t={EX_NEG} icon={ChipIcons.doc} label="日報提出率が低下（92% → 71%）" note="日報提出率の低下" />
        <ExSignalRow t={EX_NEG} icon={ExIcons.clock} label="稼働時間が基準を超過（当月 192.5h）" note="高稼働" />
        <ExSurveyRow t={EX_WARN} q="チーム内の人間関係" reason="回答が2ポイント" prev={3} cur={2} hist={[4, 3, 3, 3, 2]} id="exsp2pt" />
        <ExSurveyRow t={EX_NEG} q="仕事内容満足度" reason="回答が1ポイント" prev={3} cur={1} hist={[4, 4, 3, 3, 1]} id="exsp1pt" />
        <ExSignalRow t={EX_WARN} icon={ExIcons.repeat} label="期限切れ回答が連続（5月・6月）" note="期限切れ回答の連続" last={true} />
      </div>
    </div>
  );
}

Object.assign(window, { ScreenV7A2, CheckRowCap, CheckExamplesPanel, CommentBand2, SurveyCard2, RecordCard2, AvgCompareRail, IconChip2, ChipIcons, C2, TXT2 });
