// テーマ② ICT地盤改良工ツール — 案件一覧 + ワークスペース（工程ナビ + 日々の記録）
const ThemeICT = ({ onBack }) => {
  const d = CXDATA;
  const [proj, setProj] = useState(null);     // null=list, else workspace
  const [step, setStep] = useState('daily');
  const [toast, setToast] = useState(null);
  const [report, setReport] = useState(false); // 簡易報告ウィザード

  if (report) {
    return <ReportWizard proj={proj}
      onClose={()=>setReport(false)}
      onDone={()=>{ setReport(false); setToast('施工結果を報告しました'); }}/>;
  }

  // ---------- 案件一覧 ----------
  if (!proj) {
    return (
      <div className="cx-main">
        <PageHeader crumb="ポータル / ICT地盤改良工ツール" title="案件一覧" onBack={onBack}
          actions={<><Btn kind="out" icon="camera" size="sm" onClick={()=>setReport(true)}>今日の施工結果を報告</Btn><Btn kind="out" icon="filter" size="sm">絞り込み</Btn><Btn icon="plus">新規案件</Btn></>}/>
        <div className="cx-stats" style={{gridTemplateColumns:'repeat(4,1fr)',marginBottom:20}}>
          <Stat lab="進行中" icon="building" val="3" unit="件"/>
          <Stat lab="準備中" icon="clock" val="1" unit="件"/>
          <Stat lab="集計中" icon="chart" val="1" unit="件"/>
          <Stat lab="今月完了" icon="check" val="2" unit="件"/>
        </div>
        <div className="cx-card" style={{overflow:'hidden'}}>
          <table className="cx-tbl">
            <thead><tr>
              <th>案件番号</th><th>工事名</th><th>工法</th><th>発注者</th><th>進捗</th><th className="right">杭数</th><th>工期</th><th>担当</th>
            </tr></thead>
            <tbody>
              {d.projects.map(p=>(
                <tr key={p.id} onClick={()=>{setProj(p);setStep('daily');}}>
                  <td className="mut" style={{fontFamily:'ui-monospace,Menlo,monospace',fontSize:12}}>{p.id}</td>
                  <td className="strong">{p.name}</td>
                  <td><Chip tone="accent">{p.method}</Chip></td>
                  <td className="mut">{p.client}</td>
                  <td style={{minWidth:140}}>
                    <div style={{display:'flex',alignItems:'center',gap:8}}>
                      <div className="cx-bar" style={{flex:1}}><i style={{width:p.prog+'%'}} className={p.prog===100?'':''}/></div>
                      <Chip tone={STATUS_TONE[p.status]}>{p.status}</Chip>
                    </div>
                  </td>
                  <td className="right">{p.piles}</td>
                  <td className="mut">{p.due}</td>
                  <td><div className="cx-avatar" style={{width:26,height:26,fontSize:11,background:'var(--c-primary)'}}>{p.mgr[0]}</div></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    );
  }

  // ---------- ワークスペース ----------
  const dd = d.ictDaily;
  const maxBar = Math.max(...dd.weekBars.map(b=>b.v));
  return (
    <div style={{display:'grid',gridTemplateColumns:'220px 1fr',height:'100%',minHeight:0}}>
      {/* 工程ナビ */}
      <aside className="cx-side">
        <div className="cx-nav" onClick={()=>setProj(null)} style={{color:'var(--c-text-2)',fontWeight:700,marginBottom:6}}>
          <CXIcon name="chevronLeft" size={16}/>案件一覧へ
        </div>
        <div style={{padding:'4px 8px 10px'}}>
          <div style={{fontSize:13.5,fontWeight:700,lineHeight:1.4}}>{proj.name}</div>
          <div style={{fontSize:11.5,color:'var(--c-text-3)',marginTop:4,fontFamily:'ui-monospace,Menlo,monospace'}}>{proj.id}</div>
          <div style={{marginTop:8}}><Chip tone="accent">{proj.method}</Chip></div>
        </div>
        <div className="grp">工程</div>
        {d.ictNav.map(n=>(
          <div key={n.id} className={`cx-nav${step===n.id?' active':''}${n.done?' done':''}`} onClick={()=>setStep(n.id)}>
            <span className="num">{n.done?<CXIcon name="check" size={12}/>:n.no}</span>{n.label}
            {n.cnt && <span className="cnt">{n.cnt}</span>}
          </div>
        ))}
        <div style={{marginTop:'auto',paddingTop:12}}>
          <Btn kind="out" size="sm" block icon="camera" onClick={()=>setReport(true)}>今日の施工結果を報告</Btn>
        </div>
      </aside>

      {/* 中身 */}
      <div className="cx-main">
        {step==='daily' && <ICTDaily proj={proj} dd={dd} maxBar={maxBar} onToast={setToast}/>}
        {step==='basic' && <ICTBasic proj={proj}/>}
        {step!=='daily' && step!=='basic' && <ICTPlaceholder step={d.ictNav.find(n=>n.id===step)} onToast={setToast}/>}
      </div>
      {toast && <Toast msg={toast} onDone={()=>setToast(null)}/>}
    </div>
  );
};

// 日々の記録（現場管理）— ダッシュボード
const ICTDaily = ({ proj, dd, maxBar, onToast }) => (
  <>
    <PageHeader crumb={`ICT地盤改良工ツール / ${proj.id}`} title="日々の記録（現場管理）"
      actions={<><Btn kind="out" icon="upload" size="sm">施工CSV取込</Btn><Btn icon="plus" onClick={()=>onToast('施工サイクルを記録しました')}>施工を記録</Btn></>}/>
    <div className="cx-wiz" style={{marginBottom:20}}>
      {['基本情報','工事設定','工事準備','日々の記録','集計','帳票'].map((s,i)=>(
        <React.Fragment key={s}>
          <div className={`step ${i<3?'done':i===3?'active':''}`}><span className="n">{i<3?'✓':i+1}</span>{s}</div>
          {i<5 && <div className="conn"/>}
        </React.Fragment>
      ))}
    </div>

    <div className="cx-stats" style={{marginBottom:18}}>{dd.stats.map((s,i)=><Stat key={i} {...s}/>)}</div>

    <div className="cx-grid2" style={{gridTemplateColumns:'1.4fr 1fr',alignItems:'start'}}>
      {/* バッチ記録 */}
      <div className="cx-card">
        <div className="cx-card-h"><h3>本日の施工サイクル</h3><span className="hint">AM/PM別・立会チェック済を正式記録</span></div>
        <table className="cx-tbl">
          <thead><tr><th>時刻</th><th>杭番号</th><th>サイクル</th><th>改良長</th><th className="right">スラリー比重</th><th>立会</th></tr></thead>
          <tbody>
            {dd.batches.map((b,i)=>(
              <tr key={i}>
                <td className="mut">{b.t}</td><td className="strong">{b.pile}</td><td>{b.method}</td><td>{b.depth}</td>
                <td className="right">{b.sg==='—'?<span className="mut">測定待ち</span>:b.sg}</td>
                <td>{b.wit?<Chip tone="ok" dot>記録済</Chip>:<Chip tone="warn" dot>未立会</Chip>}</td>
              </tr>
            ))}
          </tbody>
        </table>
        <div style={{padding:'12px 16px',borderTop:'1px solid var(--c-border)',display:'flex',alignItems:'center',gap:10}}>
          <CXIcon name="camera" size={16} color="#656c87"/>
          <span style={{fontSize:12.5,color:'var(--c-text-2)'}}>スラリー比重は伝票写真のOCRで自動入力できます</span>
          <Btn kind="out" size="sm" style={{marginLeft:'auto'}} onClick={()=>onToast('写真OCRを実行しました')}>写真から読取</Btn>
        </div>
      </div>

      <div style={{display:'flex',flexDirection:'column',gap:18}}>
        {/* 週次グラフ */}
        <div className="cx-card pad">
          <div style={{display:'flex',alignItems:'center',marginBottom:6}}>
            <h3 style={{fontSize:15,fontWeight:700}}>今週の施工杭数</h3>
            <span style={{marginLeft:'auto',fontSize:12,color:'var(--c-text-3)'}}>計画比 92%</span>
          </div>
          <div className="cx-chart">
            {dd.weekBars.map((b,i)=>(
              <div className="bar" key={i}><i style={{height:(b.v/maxBar*100)+'%'}}/><span>{b.d}</span></div>
            ))}
          </div>
        </div>
        {/* 在庫予測 */}
        <div className="cx-card pad">
          <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:14}}>
            <CXIcon name="box" size={17} color="#0b57c4"/><h3 style={{fontSize:15,fontWeight:700}}>固化材 在庫予測</h3>
          </div>
          <div style={{display:'flex',alignItems:'baseline',gap:6,marginBottom:8}}>
            <span style={{fontSize:28,fontWeight:700}}>8.2</span><span style={{color:'var(--c-text-3)'}}>t 残</span>
            <Chip tone="warn" dot>枯渇予測 7/24</Chip>
          </div>
          <div className="cx-bar warn" style={{marginBottom:12}}><i style={{width:'34%'}}/></div>
          <dl className="cx-kv" style={{gridTemplateColumns:'1fr auto',fontSize:12.5,rowGap:6}}>
            <dt>本日入庫</dt><dd className="strong">+ 4.0 t</dd>
            <dt>本日出庫（実績）</dt><dd className="strong">− 2.6 t</dd>
            <dt>日平均消費</dt><dd className="strong">2.4 t / 日</dd>
          </dl>
        </div>
      </div>
    </div>
  </>
);

// 基本情報（地図つき）
const ICTBasic = ({ proj }) => (
  <>
    <PageHeader crumb={`ICT地盤改良工ツール / ${proj.id}`} title="基本情報"
      actions={<Btn icon="check">保存する</Btn>}/>
    <div className="cx-grid2" style={{alignItems:'start'}}>
      <div className="cx-card pad">
        <h3 style={{fontSize:15,fontWeight:700,marginBottom:16}}>工事概要</h3>
        <dl className="cx-kv" style={{rowGap:14}}>
          <dt>工事名</dt><dd className="strong">{proj.name}</dd>
          <dt>発注者</dt><dd>{proj.client}</dd>
          <dt>工事場所</dt><dd>{proj.loc}</dd>
          <dt>採用工法</dt><dd><Chip tone="accent">{proj.method}</Chip> <Chip tone="muted">補助：薬液注入</Chip></dd>
          <dt>工期</dt><dd>2025/06/01 〜 {proj.due}</dd>
          <dt>計画杭数</dt><dd className="strong">{proj.piles} 本</dd>
          <dt>担当者</dt><dd>{proj.mgr}（東京支店 施工管理部）</dd>
        </dl>
      </div>
      <div className="cx-card pad">
        <h3 style={{fontSize:15,fontWeight:700,marginBottom:16}}>位置（緯度経度・地図）</h3>
        <div className="cx-map">
          <svg viewBox="0 0 400 240" style={{width:'100%',height:'100%'}} xmlns="http://www.w3.org/2000/svg">
            <rect width="400" height="240" fill="#e3eaf1"/>
            <g stroke="#c4d0dc" strokeWidth="1" fill="none">
              <path d="M0 60 H400 M0 120 H400 M0 180 H400 M80 0 V240 M180 0 V240 M280 0 V240"/>
              <path d="M0 150 C100 130 160 200 260 170 S400 150 400 150" stroke="#a9c4e0" strokeWidth="6"/>
            </g>
            <g fill="#cdd9e4"><rect x="120" y="70" width="46" height="34"/><rect x="200" y="92" width="38" height="40"/><rect x="96" y="128" width="40" height="30"/></g>
          </svg>
          <div className="pin" style={{left:'52%',top:'56%'}}><CXIcon name="pin" size={30} color="#ff3366"/></div>
        </div>
        <div style={{display:'flex',gap:20,marginTop:12,fontSize:12.5,color:'var(--c-text-2)'}}>
          <div><span className="mut">緯度</span> <b>35.5308</b></div>
          <div><span className="mut">経度</span> <b>139.7029</b></div>
          <Btn kind="ghost" size="sm" icon="link" style={{marginLeft:'auto'}}>地図で開く</Btn>
        </div>
      </div>
    </div>
  </>
);

const ICTPlaceholder = ({ step, onToast }) => (
  <>
    <PageHeader crumb="ICT地盤改良工ツール" title={step.label}/>
    <div className="cx-card pad" style={{textAlign:'center',padding:'56px 24px'}}>
      <div style={{width:56,height:56,borderRadius:14,background:'var(--c-primary-bg)',color:'var(--c-primary)',display:'flex',alignItems:'center',justifyContent:'center',margin:'0 auto 16px'}}>
        <CXIcon name="fileText" size={26}/>
      </div>
      <h3 style={{fontSize:16,fontWeight:700,marginBottom:8}}>{step.label} のUIはこの工程で扱います</h3>
      <p style={{fontSize:13.5,color:'var(--c-text-2)',lineHeight:1.8,maxWidth:460,margin:'0 auto 20px'}}>
        数量表・配合管理・出来形・総括表・事後調査などを工程順に扱い、最後に帳票として出力します。
      </p>
      <Btn icon="download" onClick={()=>onToast(step.label+'のサンプル帳票を出力しました')}>サンプル帳票を出力</Btn>
    </div>
  </>
);

window.ThemeICT = ThemeICT;
