// ─────────────────────────────────────────────────────────────────────────
//  screens-employee2.jsx — 機能画面 E-03 / E-04 / E-05 / E-07 / E-11
// ─────────────────────────────────────────────────────────────────────────

// ── E-03 従業員所在検索 ─────────────────────────────────────────────────────
const PEOPLE = [
  { name: '田中 太郎', dept: '戦略コンサルティング', floor: '14F', area: 'C島 / 席 C-14', status: '在席', tone: 'green', init: '田', island: 'C', since: '13:30', detail: '13:30 から在席（約 1時間20分）' },
  { name: '田中 美咲', dept: 'リスクアドバイザリー', floor: '14F', area: 'A島 / 席 A-08', status: '会議中', tone: 'amber', init: '田', island: 'A', since: '14:10', detail: '14:10 から会議室14-A（〜15:00）' },
  { name: '佐藤 健', dept: 'テクノロジー', floor: '14F', area: 'B島 / 席 B-22', status: '離席', tone: 'neutral', init: '佐', island: 'B', since: null, detail: '最終在席 13:20（15分前）' },
];

function E03_Locate({ nav, back }) {
  const [sel, setSel] = useState(0);
  const p = PEOPLE[sel];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <EmpStatusBar onHome={() => nav('E-01')} />
      <BackHeader title="従業員所在検索" sub="Colorkrew Biz 連携" back={back} />
      <div style={{ flex: 1, display: 'flex', gap: 20, padding: '0 28px 24px', minHeight: 0 }}>
        {/* left: search + list */}
        <div style={{ width: 360, display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, background: EMP.surface,
            border: `1px solid ${EMP.line}`, borderRadius: 14, padding: '0 16px', height: 54 }}>
            <Icon name="search" size={20} color={EMP.faint} />
            <input defaultValue="田中" style={{ flex: 1, background: 'transparent', border: 'none', outline: 'none',
              color: EMP.text, fontSize: 17 }} />
          </div>
          <div style={{ color: EMP.faint, fontSize: 13 }}>3件の候補</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, overflowY: 'auto' }}>
            {PEOPLE.map((pp, i) => (
              <button key={i} onClick={() => setSel(i)} style={{ textAlign: 'left', cursor: 'pointer',
                background: i === sel ? 'rgba(14,156,132,0.12)' : EMP.surface,
                border: `1px solid ${i === sel ? EMP.blue : EMP.line}`, borderRadius: 14, padding: 14,
                display: 'flex', alignItems: 'center', gap: 13 }}>
                <div style={{ width: 46, height: 46, borderRadius: 12, background: EMP.surface2, color: EMP.text,
                  display: 'grid', placeItems: 'center', fontSize: 19, fontWeight: 700 }}>{pp.init}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ color: EMP.text, fontSize: 17, fontWeight: 700 }}>{pp.name}</div>
                  <div style={{ color: EMP.faint, fontSize: 13 }}>{pp.dept}</div>
                  <div style={{ color: pp.tone === 'green' ? EMP.green : EMP.faint, fontSize: 12.5, marginTop: 3, display: 'flex', alignItems: 'center', gap: 4 }}>
                    <Icon name="clock" size={12} />{pp.since ? `${pp.since}から在席` : '離席中'}</div>
                </div>
                <Pill tone={pp.tone}>{pp.status}</Pill>
              </button>
            ))}
          </div>
        </div>
        {/* right: map + detail */}
        <div style={{ flex: 1, background: EMP.surface, border: `1px solid ${EMP.line}`, borderRadius: 18,
          display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
          <div style={{ flex: 1, position: 'relative', background: '#EEF1F4', minHeight: 0 }}>
            <FloorPlan island={p.island} name={`${p.name}さん`} />
            <div style={{ position: 'absolute', top: 16, left: 16, background: 'rgba(255,255,255,0.92)',
              borderRadius: 10, padding: '8px 14px', color: EMP.text, fontSize: 14, fontWeight: 600,
              backdropFilter: 'blur(6px)' }}>{p.floor} フロアマップ</div>
          </div>
          <div style={{ padding: '18px 24px', borderTop: `1px solid ${EMP.line}` }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 10 }}>
              <div style={{ color: EMP.text, fontSize: 22, fontWeight: 700 }}>{p.name}</div>
              <Pill tone={p.tone}>{p.status}</Pill>
              <span style={{ marginLeft: 'auto', color: EMP.sub, fontSize: 15, display: 'flex', alignItems: 'center', gap: 6 }}>
                <Icon name="mapPin" size={17} color={EMP.blue} />{p.floor}　{p.area}</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 16, color: p.since ? EMP.green : EMP.sub, fontSize: 14.5, fontWeight: 600 }}>
              <Icon name="clock" size={17} />{p.detail}</div>
            <div style={{ display: 'flex', gap: 12 }}>
              <ActionBtn icon="send" label="Teamsで通知" onClick={() => nav('E-DONE', { title: `${p.name}さんへ通知しました`, sub: 'Teams にメッセージを送信しました' })} />
              <ActionBtn icon="package" label="ここへ届ける" primary onClick={() => nav('E-05')} />
              <ActionBtn icon="route" label="近くまで移動" onClick={() => nav('E-DONE', { title: '移動を開始しました', sub: `${p.area} 付近へ向かいます` })} />
            </div>
          </div>
        </div>
      </div>
      <EmpNav active="E-01" nav={nav} />
    </div>
  );
}

// ── Floor plan (map-like) + path helpers ──────────────────────────────────
const ISLAND_SEAT = { A: [145, 250], B: [365, 250], C: [585, 250] };
function ptAlong(pts, t) {
  let segs = [], total = 0;
  for (let i = 0; i < pts.length - 1; i++) { const d = Math.hypot(pts[i + 1][0] - pts[i][0], pts[i + 1][1] - pts[i][1]); segs.push(d); total += d; }
  let dist = t * total;
  for (let i = 0; i < segs.length; i++) { if (dist <= segs[i] || i === segs.length - 1) { const f = segs[i] ? dist / segs[i] : 0; return [pts[i][0] + (pts[i + 1][0] - pts[i][0]) * f, pts[i][1] + (pts[i + 1][1] - pts[i][1]) * f]; } dist -= segs[i]; }
  return pts[pts.length - 1];
}
function traveled(pts, t) {
  const out = [pts[0].slice()]; let segs = [], total = 0;
  for (let i = 0; i < pts.length - 1; i++) { const d = Math.hypot(pts[i + 1][0] - pts[i][0], pts[i + 1][1] - pts[i][1]); segs.push(d); total += d; }
  let dist = t * total;
  for (let i = 0; i < segs.length; i++) { if (dist <= segs[i]) { const f = segs[i] ? dist / segs[i] : 0; out.push([pts[i][0] + (pts[i + 1][0] - pts[i][0]) * f, pts[i][1] + (pts[i + 1][1] - pts[i][1]) * f]); return out; } out.push(pts[i + 1].slice()); dist -= segs[i]; }
  return out;
}

function FloorPlan({ accent = '#0B7A6B', island = 'C', sinceLabel, name, robotT = null }) {
  const seat = ISLAND_SEAT[island] || ISLAND_SEAT.C;
  const dock = [60, 384];
  const path = [dock, [60, 337], [seat[0], 337], [seat[0], seat[1] + 28]];
  const rb = robotT != null ? ptAlong(path, robotT) : null;
  const tp = robotT != null ? traveled(path, robotT) : null;
  const rooms = [
    { x: 36, w: 128, t: '会議室 14-A' }, { x: 176, w: 128, t: '会議室 14-B' },
    { x: 316, w: 84, t: 'Focus 1' }, { x: 412, w: 84, t: 'Focus 2' }, { x: 508, w: 176, t: '休憩・カフェ' },
  ];
  const islands = [{ k: 'A', x: 70, w: 150 }, { k: 'B', x: 290, w: 150 }, { k: 'C', x: 510, w: 150 }];
  const line = '#E3E7EC';
  const lx = Math.min(Math.max(seat[0], 110), 610);
  return (
    <svg viewBox="0 0 720 440" style={{ width: '100%', height: '100%' }} preserveAspectRatio="xMidYMid meet">
      <defs>
        <pattern id="fpDots" width="22" height="22" patternUnits="userSpaceOnUse">
          <circle cx="1.2" cy="1.2" r="1.2" fill="rgba(0,0,0,0.05)" />
        </pattern>
      </defs>
      <rect x="20" y="20" width="680" height="400" rx="18" fill="#F8FAFB" stroke={line} strokeWidth="1.5" />
      <rect x="20" y="20" width="680" height="400" rx="18" fill="url(#fpDots)" />
      {/* corridors */}
      <rect x="40" y="325" width="640" height="26" rx="6" fill="rgba(11,122,107,0.06)" />
      <rect x="245" y="136" width="22" height="210" rx="6" fill="rgba(11,122,107,0.05)" />
      <rect x="465" y="136" width="22" height="210" rx="6" fill="rgba(11,122,107,0.05)" />
      {/* meeting rooms */}
      {rooms.map((r, i) => (
        <g key={i}>
          <rect x={r.x} y="36" width={r.w} height="84" rx="9" fill="#FFFFFF" stroke={line} />
          <text x={r.x + r.w / 2} y="83" textAnchor="middle" fill="#5C6B76" fontSize="14" fontWeight="600">{r.t}</text>
        </g>
      ))}
      {/* desk islands */}
      {islands.map((is, i) => (
        <g key={i}>
          <text x={is.x + is.w / 2} y="178" textAnchor="middle" fill="#5C6B76" fontSize="13" fontWeight="700">{is.k}島</text>
          <rect x={is.x} y="188" width={is.w} height="126" rx="12" fill={`${accent}12`} stroke={`${accent}40`} />
          {[0, 1, 2, 3, 4, 5].map(d => {
            const c = d % 3, r = Math.floor(d / 3);
            return <rect key={d} x={is.x + 16 + c * 42} y={204 + r * 54} width="30" height="38" rx="5"
              fill="#FFFFFF" stroke="#DCE2E7" />;
          })}
        </g>
      ))}
      {/* entrance / EV */}
      <rect x="26" y="150" width="38" height="150" rx="9" fill="rgba(0,0,0,0.035)" stroke={line} strokeDasharray="4 4" />
      <text x="45" y="225" textAnchor="middle" fill="#94A2AC" fontSize="12" transform="rotate(-90 45 225)">EV・受付</text>
      {/* path + dock */}
      {robotT != null && <>
        <polyline points={path.map(p => p.join(',')).join(' ')} fill="none" stroke={`${accent}45`} strokeWidth="3" strokeDasharray="6 8" strokeLinecap="round" />
        {tp && <polyline points={tp.map(p => p.join(',')).join(' ')} fill="none" stroke={accent} strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round" />}
      </>}
      <circle cx={dock[0]} cy={dock[1]} r="7" fill="none" stroke="#94A2AC" strokeWidth="2" />
      <rect x="30" y="362" width="92" height="22" rx="6" fill="#EEF1F4" stroke={line} />
      <text x="76" y="377" textAnchor="middle" fill="#5C6B76" fontSize="12">充電ドック</text>
      {/* target pin */}
      <g transform={`translate(${seat[0]}, ${seat[1]})`}>
        <circle r="18" fill={`${accent}22`}><animate attributeName="r" values="13;24;13" dur="2s" repeatCount="indefinite" /><animate attributeName="opacity" values="0.6;0;0.6" dur="2s" repeatCount="indefinite" /></circle>
        <circle r="9" fill={accent} /><circle r="3.5" fill="#fff" />
      </g>
      {/* label */}
      <g transform={`translate(${lx}, ${seat[1] - (sinceLabel ? 60 : 52)})`}>
        {sinceLabel ? <>
          <rect x="-90" y="-26" width="180" height="46" rx="10" fill="#FFFFFF" stroke={`${accent}66`} strokeWidth="1.5" />
          <text x="0" y="-5" textAnchor="middle" fill="#1F2A33" fontSize="15" fontWeight="700">{name || '対象者'}</text>
          <text x="0" y="13" textAnchor="middle" fill={accent} fontSize="12.5" fontWeight="600">{sinceLabel}</text>
        </> : <>
          <rect x="-78" y="-18" width="156" height="34" rx="9" fill="#FFFFFF" stroke={`${accent}66`} strokeWidth="1.5" />
          <text x="0" y="4" textAnchor="middle" fill="#1F2A33" fontSize="15" fontWeight="700">{name || '対象者'}</text>
        </>}
      </g>
      {/* robot */}
      {rb && <g transform={`translate(${rb[0]}, ${rb[1]})`}>
        <circle r="20" fill="none" stroke={accent} strokeWidth="2" opacity="0.4"><animate attributeName="r" values="15;26;15" dur="1.4s" repeatCount="indefinite" /><animate attributeName="opacity" values="0.5;0;0.5" dur="1.4s" repeatCount="indefinite" /></circle>
        <rect x="-16" y="-16" width="32" height="32" rx="9" fill={accent} stroke="#fff" strokeWidth="1.5" />
        <circle cx="-5" cy="-3" r="2.6" fill="#fff" /><circle cx="5" cy="-3" r="2.6" fill="#fff" />
        <rect x="-7" y="5" width="14" height="3" rx="1.5" fill="rgba(255,255,255,0.85)" />
      </g>}
    </svg>
  );
}

function ActionBtn({ icon, label, onClick, primary }) {
  return (
    <button onClick={onClick} style={{ flex: 1, height: 56, cursor: 'pointer', borderRadius: 14,
      border: primary ? 'none' : `1px solid ${EMP.line}`, background: primary ? EMP.blue : EMP.surface2,
      color: primary ? '#fff' : EMP.text, fontSize: 16, fontWeight: 600, display: 'flex',
      alignItems: 'center', justifyContent: 'center', gap: 9 }}>
      <Icon name={icon} size={21} />{label}
    </button>
  );
}

// ── E-04 会議室検索・予約 ────────────────────────────────────────────────────
const ROOMS = [
  { name: '会議室 14-A', cap: 6, dist: '20m', floor: '14F', slot: '14:00 – 15:00', equip: ['モニター', 'WEB会議'], free: true },
  { name: '会議室 14-C', cap: 4, dist: '35m', floor: '14F', slot: '14:00 – 15:30', equip: ['ホワイトボード'], free: true },
  { name: 'Focus Room 2', cap: 4, dist: '12m', floor: '14F', slot: '14:30 – 15:00', equip: ['WEB会議'], free: true },
  { name: '会議室 12-B', cap: 8, dist: '1F下', floor: '12F', slot: '満室', equip: ['大型モニター'], free: false },
];

function E04_Room({ nav, back }) {
  const [sel, setSel] = useState(0);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <EmpStatusBar onHome={() => nav('E-01')} />
      <BackHeader title="会議室 検索・予約" sub="Microsoft Graph API 連携" back={back} />
      <div style={{ flex: 1, display: 'flex', gap: 20, padding: '0 28px 24px', minHeight: 0 }}>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
          <div style={{ display: 'flex', gap: 10, marginBottom: 14, flexWrap: 'wrap' }}>
            {['本日 14:00–15:00', '4名', '14F 優先', 'WEB会議あり'].map(c => (
              <span key={c} style={{ padding: '8px 14px', borderRadius: 999, background: 'rgba(14,156,132,0.12)',
                border: `1px solid ${EMP.blue}44`, color: '#0B7A6B', fontSize: 14, fontWeight: 600 }}>{c}</span>
            ))}
          </div>
          <div style={{ color: EMP.faint, fontSize: 13, marginBottom: 10 }}>空き状況（{ROOMS.filter(r => r.free).length}件）</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, overflowY: 'auto' }}>
            {ROOMS.map((r, i) => (
              <button key={i} disabled={!r.free} onClick={() => setSel(i)} style={{ textAlign: 'left',
                cursor: r.free ? 'pointer' : 'not-allowed', opacity: r.free ? 1 : 0.45,
                background: i === sel ? 'rgba(14,156,132,0.12)' : EMP.surface,
                border: `1px solid ${i === sel ? EMP.blue : EMP.line}`, borderRadius: 14, padding: '16px 18px',
                display: 'flex', alignItems: 'center', gap: 16 }}>
                <div style={{ width: 52, height: 52, borderRadius: 13, background: EMP.surface2, display: 'grid', placeItems: 'center' }}>
                  <Icon name="calendar" size={26} color={r.free ? EMP.blue : EMP.faint} />
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ color: EMP.text, fontSize: 18, fontWeight: 700 }}>{r.name}</div>
                  <div style={{ color: EMP.sub, fontSize: 14, marginTop: 3, display: 'flex', gap: 14 }}>
                    <span><Icon name="users" size={14} style={{ verticalAlign: -2, marginRight: 4 }} />{r.cap}名</span>
                    <span>{r.floor}・{r.dist}</span>
                    <span>{r.equip.join('・')}</span>
                  </div>
                </div>
                <Pill tone={r.free ? 'green' : 'red'}>{r.free ? r.slot : r.slot}</Pill>
              </button>
            ))}
          </div>
        </div>
        {/* booking summary */}
        <div style={{ width: 320, background: EMP.surface, border: `1px solid ${EMP.line}`, borderRadius: 18, padding: 22,
          display: 'flex', flexDirection: 'column' }}>
          <div style={{ color: EMP.faint, fontSize: 13, fontWeight: 600, letterSpacing: '0.06em', marginBottom: 14 }}>予約内容</div>
          <div style={{ color: EMP.text, fontSize: 22, fontWeight: 700, marginBottom: 4 }}>{ROOMS[sel].name}</div>
          <div style={{ color: EMP.sub, fontSize: 15, marginBottom: 20 }}>{ROOMS[sel].slot}・{ROOMS[sel].cap}名</div>
          {[['件名', 'チーム定例'], ['主催', 'あなた'], ['通知', '参加者へ自動送信']].map(([k, v]) => (
            <div key={k} style={{ display: 'flex', justifyContent: 'space-between', padding: '11px 0', borderBottom: `1px solid ${EMP.line}` }}>
              <span style={{ color: EMP.faint, fontSize: 14 }}>{k}</span>
              <span style={{ color: EMP.text, fontSize: 15, fontWeight: 600 }}>{v}</span>
            </div>
          ))}
          <div style={{ flex: 1 }}></div>
          <button onClick={() => nav('E-DONE', { title: '会議室を予約しました', sub: `${ROOMS[sel].name}・${ROOMS[sel].slot}`, calendar: true })}
            style={{ height: 60, border: 'none', cursor: 'pointer', borderRadius: 15, background: EMP.blue, color: '#fff',
            fontSize: 18, fontWeight: 700, marginBottom: 10, boxShadow: '0 8px 24px rgba(14,156,132,0.34)' }}>予約する</button>
          <button style={{ height: 50, cursor: 'pointer', borderRadius: 13, background: 'transparent',
            border: `1px solid ${EMP.line}`, color: EMP.sub, fontSize: 15, fontWeight: 600 }}>別候補を見る</button>
        </div>
      </div>
      <EmpNav active="E-01" nav={nav} />
    </div>
  );
}

// ── E-05 配送依頼 ────────────────────────────────────────────────────────────
function E05_Delivery({ nav, back }) {
  const [cargo, setCargo] = useState('資料');
  const [tray, setTray] = useState('中段');
  const cargos = [['資料', 'doc'], ['郵便', 'mail'], ['備品', 'package'], ['飲料', 'coffee'], ['お土産', 'gift']];
  const trays = ['上段', '中段', '下段'];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <EmpStatusBar onHome={() => nav('E-01')} />
      <BackHeader title="配送依頼" sub="同一フロア内の物品配送" back={back} />
      <div style={{ flex: 1, display: 'flex', gap: 20, padding: '0 28px 24px', minHeight: 0, overflowY: 'auto' }}>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 20 }}>
          {/* 宛先 */}
          <Section label="宛先">
            <div style={{ display: 'flex', alignItems: 'center', gap: 13, background: EMP.surface2, borderRadius: 13, padding: 14 }}>
              <div style={{ width: 46, height: 46, borderRadius: 12, background: EMP.surface, display: 'grid', placeItems: 'center', fontSize: 18, fontWeight: 700, color: EMP.text }}>田</div>
              <div style={{ flex: 1 }}>
                <div style={{ color: EMP.text, fontSize: 17, fontWeight: 700 }}>田中 太郎さん</div>
                <div style={{ color: EMP.faint, fontSize: 14 }}>14F C島 / 席 C-14</div>
              </div>
              <Pill tone="green">在席</Pill>
            </div>
          </Section>
          {/* 荷物 */}
          <Section label="荷物の種別">
            <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
              {cargos.map(([c, ic]) => (
                <button key={c} onClick={() => setCargo(c)} style={{ cursor: 'pointer', borderRadius: 13, padding: '14px 18px',
                  background: cargo === c ? 'rgba(14,156,132,0.14)' : EMP.surface2,
                  border: `1px solid ${cargo === c ? EMP.blue : 'transparent'}`, color: cargo === c ? '#0B7A6B' : EMP.text,
                  display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 7, width: 96, fontSize: 15, fontWeight: 600 }}>
                  <Icon name={ic} size={26} color={cargo === c ? EMP.blue : EMP.sub} />{c}
                </button>
              ))}
            </div>
          </Section>
          {/* 置き場所 */}
          <Section label="トレイ位置">
            <div style={{ display: 'flex', gap: 10 }}>
              {trays.map(t => (
                <button key={t} onClick={() => setTray(t)} style={{ flex: 1, cursor: 'pointer', height: 56, borderRadius: 13,
                  background: tray === t ? 'rgba(14,156,132,0.14)' : EMP.surface2, border: `1px solid ${tray === t ? EMP.blue : 'transparent'}`,
                  color: tray === t ? '#0B7A6B' : EMP.text, fontSize: 16, fontWeight: 600 }}>{t}トレイ</button>
              ))}
            </div>
          </Section>
        </div>
        {/* summary */}
        <div style={{ width: 320, background: EMP.surface, border: `1px solid ${EMP.line}`, borderRadius: 18, padding: 22, display: 'flex', flexDirection: 'column' }}>
          <div style={{ color: EMP.faint, fontSize: 13, fontWeight: 600, letterSpacing: '0.06em', marginBottom: 16 }}>配送前チェック</div>
          {[['荷物をトレイに置いた', true], ['配送先は同一フロア', true], ['走行可能な時間帯', true], ['宛先へTeams通知', true]].map(([k, ok]) => (
            <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '11px 0', borderBottom: `1px solid ${EMP.line}` }}>
              <Icon name="checkCircle" size={20} color={EMP.green} />
              <span style={{ color: EMP.text, fontSize: 15 }}>{k}</span>
            </div>
          ))}
          <div style={{ marginTop: 18, background: EMP.surface2, borderRadius: 13, padding: '14px 16px', fontSize: 14, color: EMP.sub, lineHeight: 1.7 }}>
            {cargo} を <b style={{ color: EMP.text }}>{tray}トレイ</b> から<br />田中さん（14F C島）へ配送します
          </div>
          <div style={{ flex: 1 }}></div>
          <button onClick={() => nav('E-06', { cargo, tray })} style={{ height: 60, border: 'none', cursor: 'pointer',
            borderRadius: 15, background: EMP.blue, color: '#fff', fontSize: 18, fontWeight: 700,
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, boxShadow: '0 8px 24px rgba(14,156,132,0.34)' }}>
            <Icon name="package" size={23} />配送開始
          </button>
        </div>
      </div>
      <EmpNav active="E-01" nav={nav} />
    </div>
  );
}

function Section({ label, children }) {
  return (
    <div>
      <div style={{ color: EMP.faint, fontSize: 13, fontWeight: 600, letterSpacing: '0.06em', marginBottom: 10 }}>{label}</div>
      {children}
    </div>
  );
}

// ── E-06 配送中・到着確認 ────────────────────────────────────────────────────
function E06_Transit({ nav, back, ctx }) {
  const [prog, setProg] = useState(0);
  const [paused, setPaused] = useState(false);
  useEffect(() => {
    if (paused) return;
    const id = setInterval(() => setProg(p => Math.min(p + 1, 100)), 70);
    return () => clearInterval(id);
  }, [paused]);
  const arrived = prog >= 100;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <EmpStatusBar onHome={() => nav('E-01')} />
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', padding: '18px 28px 0', minHeight: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 12 }}>
          <Pill tone={arrived ? 'green' : 'blue'} style={{ fontSize: 15 }}>
            <Icon name={arrived ? 'checkCircle' : 'route'} size={17} />{arrived ? '配送完了' : paused ? '一時停止中' : '配送中'}</Pill>
          <div>
            <div style={{ color: EMP.text, fontSize: 21, fontWeight: 700 }}>{arrived ? '田中さんへお届けしました' : '田中さんへお届け中です'}</div>
            <div style={{ color: EMP.sub, fontSize: 14 }}>{(ctx?.cargo) || '資料'}・{(ctx?.tray) || '中段'}トレイ → 14F C島 / 席 C-14</div>
          </div>
          <div style={{ marginLeft: 'auto', textAlign: 'right' }}>
            <div style={{ color: EMP.faint, fontSize: 13 }}>到着まで</div>
            <div style={{ color: arrived ? EMP.green : EMP.blue, fontSize: 26, fontWeight: 800, fontVariantNumeric: 'tabular-nums' }}>
              {arrived ? '到着' : `約${Math.ceil((100 - prog) / 100 * 42)}秒`}</div>
          </div>
        </div>
        {/* live map with moving robot */}
        <div style={{ flex: 1, background: EMP.surface, border: `1px solid ${EMP.line}`, borderRadius: 18, overflow: 'hidden', position: 'relative', minHeight: 0 }}>
          <div style={{ position: 'absolute', top: 14, left: 16, zIndex: 2, background: 'rgba(255,255,255,0.92)', borderRadius: 10,
            padding: '7px 13px', color: EMP.text, fontSize: 13, fontWeight: 600, backdropFilter: 'blur(6px)' }}>14F フロアマップ・走行中</div>
          <div style={{ position: 'absolute', top: 14, right: 16, zIndex: 2, display: 'flex', gap: 8, alignItems: 'center',
            background: 'rgba(255,255,255,0.92)', borderRadius: 10, padding: '7px 13px', backdropFilter: 'blur(6px)' }}>
            <span style={{ color: EMP.faint, fontSize: 12 }}>走行距離</span>
            <span style={{ color: EMP.text, fontSize: 13, fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>{Math.round(prog * 0.62)} / 62m</span>
          </div>
          <FloorPlan island="C" name="田中 太郎さん" sinceLabel={arrived ? 'お届け完了' : '配送先 / 席 C-14'} robotT={prog / 100} />
        </div>
        {/* controls */}
        <div style={{ display: 'flex', gap: 12, padding: '16px 0 22px' }}>
          {arrived
            ? <button onClick={() => nav('E-DONE', { title: '配送が完了しました', sub: '田中さんへTeamsで通知済みです' })} style={{ flex: 1, height: 58, border: 'none', cursor: 'pointer', borderRadius: 15, background: EMP.green, color: '#fff', fontSize: 18, fontWeight: 700 }}>完了</button>
            : <>
              <ActionBtn icon={paused ? 'play' : 'pause'} label={paused ? '再開' : '一時停止'} onClick={() => setPaused(p => !p)} />
              <ActionBtn icon="stop" label="中止してホームへ" onClick={() => nav('E-01')} />
            </>}
        </div>
      </div>
      <EmpNav active="E-ACT" nav={nav} />
    </div>
  );
}

// ── E-07 社内FAQ ─────────────────────────────────────────────────────────────
function E07_FAQ({ nav, back }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <EmpStatusBar onHome={() => nav('E-01')} />
      <BackHeader title="社内FAQ" sub="Sherpa AI 連携" back={back} />
      <div style={{ flex: 1, padding: '0 28px 20px', display: 'flex', flexDirection: 'column', minHeight: 0 }}>
        <div style={{ flex: 1, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 16, paddingRight: 6 }}>
          {/* question */}
          <div style={{ alignSelf: 'flex-end', maxWidth: '70%', background: EMP.blue, color: '#fff',
            padding: '14px 20px', borderRadius: '18px 18px 4px 18px', fontSize: 17, fontWeight: 500 }}>
            在宅勤務の申請方法を教えて</div>
          {/* answer */}
          <div style={{ alignSelf: 'flex-start', maxWidth: '78%' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8, color: EMP.faint, fontSize: 13 }}>
              <div style={{ width: 24, height: 24, borderRadius: 7, background: 'rgba(14,156,132,0.16)', display: 'grid', placeItems: 'center' }}>
                <Icon name="robot" size={15} color={EMP.blue} /></div>Sherpa AI</div>
            <div style={{ background: EMP.surface, border: `1px solid ${EMP.line}`, padding: '18px 22px',
              borderRadius: '4px 18px 18px 18px', color: EMP.text, fontSize: 16.5, lineHeight: 1.8 }}>
              在宅勤務は <b>勤務管理システム</b> から前営業日の17時までに申請します。手順は次のとおりです。
              <ol style={{ margin: '12px 0 0', paddingLeft: 22, color: EMP.sub, lineHeight: 2 }}>
                <li>勤務管理システムにログイン</li>
                <li>「在宅勤務申請」を選択し日付を指定</li>
                <li>上長承認後に確定</li>
              </ol>
              <div style={{ marginTop: 16, display: 'flex', alignItems: 'center', gap: 8, color: EMP.faint, fontSize: 13,
                borderTop: `1px solid ${EMP.line}`, paddingTop: 12 }}>
                <Icon name="doc" size={15} />参照元：就業規則 第32条 / 在宅勤務ガイドライン v3
              </div>
            </div>
            {/* actions */}
            <div style={{ display: 'flex', gap: 9, marginTop: 12, flexWrap: 'wrap' }}>
              {[['volume', '読み上げる'], ['send', 'Teamsに送る'], ['users', '担当部署に問い合わせる']].map(([ic, l]) => (
                <button key={l} style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 7, padding: '9px 16px',
                  borderRadius: 999, background: EMP.surface, border: `1px solid ${EMP.line}`, color: EMP.sub, fontSize: 14, fontWeight: 600 }}>
                  <Icon name={ic} size={16} />{l}</button>
              ))}
            </div>
          </div>
          {/* related */}
          <div style={{ marginTop: 4 }}>
            <div style={{ color: EMP.faint, fontSize: 13, marginBottom: 8 }}>関連する質問</div>
            <div style={{ display: 'flex', gap: 9, flexWrap: 'wrap' }}>
              {['経費精算の締め日は？', '会議室の予約上限は？', 'ゲストWi-Fiの使い方', '社用PCの故障時は？'].map(q => (
                <span key={q} style={{ padding: '9px 16px', borderRadius: 999, background: 'rgba(14,156,132,0.1)',
                  border: `1px solid ${EMP.blue}33`, color: '#0B7A6B', fontSize: 14, cursor: 'pointer' }}>{q}</span>
              ))}
            </div>
          </div>
        </div>
        {/* input */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, background: EMP.surface, border: `1px solid ${EMP.line}`,
          borderRadius: 16, padding: '0 10px 0 20px', height: 60, marginTop: 14 }}>
          <input placeholder="質問を入力、またはマイクで話す" style={{ flex: 1, background: 'transparent', border: 'none',
            outline: 'none', color: EMP.text, fontSize: 16 }} />
          <button style={{ width: 44, height: 44, borderRadius: 11, border: 'none', cursor: 'pointer', background: EMP.surface2, color: EMP.blue, display: 'grid', placeItems: 'center' }}><Icon name="mic" size={22} /></button>
          <button style={{ width: 44, height: 44, borderRadius: 11, border: 'none', cursor: 'pointer', background: EMP.blue, color: '#fff', display: 'grid', placeItems: 'center' }}><Icon name="send" size={20} /></button>
        </div>
      </div>
      <EmpNav active="E-01" nav={nav} />
    </div>
  );
}

// ── E-11 タスク履歴 ──────────────────────────────────────────────────────────
const TASKS = [
  { t: '配送', d: '資料を田中さんへ（14F C島）', time: '今', status: '配送中', tone: 'blue', icon: 'package' },
  { t: '会議室予約', d: '会議室 14-A・14:00–15:00', time: '5分前', status: '完了', tone: 'green', icon: 'calendar' },
  { t: '所在検索', d: '佐藤 健さんの所在を表示', time: '23分前', status: '完了', tone: 'green', icon: 'person' },
  { t: 'FAQ', d: '在宅勤務の申請方法', time: '1時間前', status: '完了', tone: 'green', icon: 'faq' },
  { t: '配送', d: 'お茶を会議室12-Bへ', time: '今朝 9:40', status: '完了', tone: 'green', icon: 'coffee' },
  { t: '巡回点検', d: '夜間パトロール（施錠確認）', time: '昨日 22:00', status: '完了', tone: 'green', icon: 'shield' },
];

function E11_History({ nav, back }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <EmpStatusBar onHome={() => nav('E-01')} />
      <BackHeader title="タスク履歴" sub="あなたの依頼" back={() => nav('E-01')} />
      <div style={{ flex: 1, padding: '0 28px 24px', overflowY: 'auto' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {TASKS.map((t, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 16, background: EMP.surface,
              border: `1px solid ${EMP.line}`, borderRadius: 14, padding: '16px 20px' }}>
              <div style={{ width: 48, height: 48, borderRadius: 12, background: EMP.surface2, display: 'grid', placeItems: 'center' }}>
                <Icon name={t.icon} size={24} color={EMP.blue} /></div>
              <div style={{ flex: 1 }}>
                <div style={{ color: EMP.text, fontSize: 17, fontWeight: 700 }}>{t.t}</div>
                <div style={{ color: EMP.sub, fontSize: 14, marginTop: 2 }}>{t.d}</div>
              </div>
              <span style={{ color: EMP.faint, fontSize: 14 }}>{t.time}</span>
              <Pill tone={t.tone}>{t.status}</Pill>
              <button style={{ width: 42, height: 42, borderRadius: 11, cursor: 'pointer', border: `1px solid ${EMP.line}`,
                background: 'transparent', color: EMP.sub, display: 'grid', placeItems: 'center' }}>
                <Icon name={t.status === '配送中' ? 'chevron' : 'refresh'} size={19} /></button>
            </div>
          ))}
        </div>
      </div>
      <EmpNav active="E-11" nav={nav} />
    </div>
  );
}

// ── E-DONE 汎用 完了画面 ─────────────────────────────────────────────────────
function EDone({ nav, ctx }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <EmpStatusBar onHome={() => nav('E-01')} />
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 40 }}>
        <div style={{ width: 96, height: 96, borderRadius: 99, background: 'rgba(34,197,126,0.16)', display: 'grid', placeItems: 'center', marginBottom: 24, animation: 'pop .4s ease' }}>
          <Icon name="checkCircle" size={56} color={EMP.green} stroke={2.2} />
        </div>
        <div style={{ color: EMP.text, fontSize: 28, fontWeight: 700, marginBottom: 8, textAlign: 'center' }}>{ctx?.title || '完了しました'}</div>
        <div style={{ color: EMP.sub, fontSize: 16, marginBottom: 36, textAlign: 'center' }}>{ctx?.sub || ''}</div>
        <div style={{ display: 'flex', gap: 12 }}>
          <button onClick={() => nav('E-01')} style={{ height: 56, padding: '0 32px', border: 'none', cursor: 'pointer', borderRadius: 14, background: EMP.blue, color: '#fff', fontSize: 17, fontWeight: 700 }}>ホームへ</button>
          {ctx?.calendar && <button onClick={() => nav('E-09')} style={{ height: 56, padding: '0 28px', cursor: 'pointer', borderRadius: 14, background: EMP.surface, border: `1px solid ${EMP.line}`, color: EMP.text, fontSize: 17, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 9 }}><Icon name="clock" size={20} color={EMP.blue} />タイムキーパーを開始</button>}
          <button onClick={() => nav('E-11')} style={{ height: 56, padding: '0 28px', cursor: 'pointer', borderRadius: 14, background: EMP.surface, border: `1px solid ${EMP.line}`, color: EMP.text, fontSize: 17, fontWeight: 600 }}>履歴を見る</button>
        </div>
      </div>
      <EmpNav active="E-01" nav={nav} />
    </div>
  );
}

Object.assign(window, { E03_Locate, E04_Room, E05_Delivery, E06_Transit, E07_FAQ, E11_History, EDone });
