// テーマ⑥ 図面数量照査 — アップロード → ファイル判別 → ①ソース別抽出結果 → ②照合結果
// UI設計仕様 v1（S-001/S-002）準拠。初期表示はアップロード画面（S-001）。
// #files / #extract / #results 付きで開くと各段階を直接表示（デモ・確認用）。
const ThemeDrawing = ({ onBack, notify }) => {
  const d = CXDATA;
  const hash = window.location.hash;
  const initPhase = (hash === '#results' || hash === '#extract') ? 'done' : (hash === '#files' ? 'files' : 'upload');
  const [phase, setPhase] = useState(initPhase);   // upload | files | running | done
  const [tab, setTab] = useState(hash === '#results' ? 'match' : 'extract');   // extract | match
  const [active, setActive] = useState(d.drawingResults[1]);
  // 判定に対する人の確認記録（BR-002: 最終判断は利用者）
  const [reviews, setReviews] = useState({});
  const [reviewLog, setReviewLog] = useState(d.drawingReviewLog);
  const addReview = (r, action, tone) => {
    const entry = { id: Date.now(), at: 'たった今', by: `${d.user.name}（${d.user.dept}）`, target: `${r.pile}・${r.item}`, action, tone };
    setReviews({ ...reviews, [r.id]: entry });
    setReviewLog([entry, ...reviewLog]);
    notify(tone==='ok' ? `${r.pile} の判定を確認済みにしました` : `${r.pile} の判定を差戻しました`);
  };

  const STATE = {
    ok:       { tone:'ok',     label:'一致' },
    mismatch: { tone:'danger', label:'不一致' },
    missing:  { tone:'warn',   label:'欠落' },
    surplus:  { tone:'primary',label:'余剰' },
  };
  const EXTRACT_STATE = {
    ok:   { tone:'ok',     label:'抽出OK' },
    warn: { tone:'warn',   label:'要確認' },
    ng:   { tone:'danger', label:'未検出' },
  };
  const counts = {
    mismatch: d.drawingResults.filter(r=>r.state==='mismatch').length,
    missing:  d.drawingResults.filter(r=>r.state==='missing').length,
    surplus:  d.drawingResults.filter(r=>r.state==='surplus').length,
    ok:       d.drawingResults.filter(r=>r.state==='ok').length,
  };

  const Disclaimer = () => (
    <div style={{textAlign:'center',fontSize:12,color:'var(--c-text-3)',padding:'18px 0 10px'}}>
      ※ ご提案用モックのため、抽出・照合結果はサンプルです。実際のUIは要件定義で確定します。
    </div>
  );

  // 位置づけバナー: 本モックは完成時の最終イメージ。まずはフェーズ1で精度検証に使う
  const PocBanner = () => (
    <div className="cx-card pad" style={{display:'flex',gap:10,alignItems:'flex-start',marginBottom:14,borderLeft:'3px solid var(--c-primary)'}}>
      <CXIcon name="alert" size={16} color="var(--c-primary)"/>
      <div style={{fontSize:12.5,color:'var(--c-text-2)',lineHeight:1.7}}>
        <b style={{color:'var(--c-text)'}}>本画面は完成時の最終イメージです。</b>
        まずはフェーズ1（検証・2026年8月〜10月）で、この画面構成のまま「平面図・数量表・断面図からどこまで正しく拾えるか（抽出精度）」と「照合判定の正しさ」を実データで検証し、その結果を踏まえて開発する範囲を確定します。
      </div>
    </div>
  );

  // ---- S-001a: アップロード ----
  if (phase==='upload') {
    return (
      <div className="cx-main">
        <PageHeader crumb="ポータル / 図面数量照査" title="杭図面の数量照査" onBack={onBack}
          actions={<Chip tone="warn">PoC</Chip>}/>
        <div style={{maxWidth:620,margin:'10px auto'}}>
          <PocBanner/>
          <div className="cx-drop">
            <div className="ic"><CXIcon name="upload" size={26}/></div>
            <div style={{fontSize:15,fontWeight:700,marginBottom:6}}>杭図面(DWG)と数量表(PDF)をアップロード</div>
            <div style={{fontSize:13,color:'var(--c-text-2)',marginBottom:18,lineHeight:1.7}}>
              図面は DWG、数量表は PDF（Excel から変換したものを含む）に対応します。<br/>
              ファイルの種別を自動で判別し、それぞれに合った処理を行います。
            </div>
            <Btn icon="upload" onClick={()=>setPhase('files')}>ファイルを選択</Btn>
          </div>
          <div className="cx-card pad" style={{marginTop:16,fontSize:12.5,color:'var(--c-text-2)',lineHeight:1.8}}>
            <b style={{color:'var(--c-text)'}}>対応形式</b><br/>
            ・図面: DWG（平面図・断面図。複数葉まとめて処理できます）<br/>
            ・数量表: PDF — テキスト埋め込みPDF（Excel等から変換）／画像スキャンPDF のどちらも投入できます。Excel ファイルは PDF に変換のうえアップロードしてください。
          </div>
          <Disclaimer/>
        </div>
      </div>
    );
  }

  // ---- S-001b: ファイル判別結果（処理経路の提示） ----
  if (phase==='files' || phase==='running') {
    return (
      <div className="cx-main">
        <PageHeader crumb="ポータル / 図面数量照査" title="アップロードファイルの判別" onBack={()=>setPhase('upload')}
          actions={<Chip tone="warn">PoC</Chip>}/>
        <div style={{maxWidth:860,margin:'10px auto'}}>
          <PocBanner/>
          <div className="cx-card" style={{overflow:'hidden'}}>
            <div className="cx-card-h"><h3>判別結果と処理経路</h3><span className="hint">3ファイル・すべて対応形式</span></div>
            <div>
              {d.uploadFiles.map(f=>(
                <div key={f.id} style={{display:'flex',gap:14,padding:'14px 16px',borderTop:'1px solid var(--c-border)',alignItems:'flex-start'}}>
                  <div style={{paddingTop:2}}><CXIcon name={f.kind==='dwg'?'ruler':'file'} size={20} color="#656c87"/></div>
                  <div style={{flex:1}}>
                    <div style={{display:'flex',alignItems:'center',gap:10,marginBottom:4}}>
                      <b style={{fontSize:13.5}}>{f.name}</b>
                      <span className="mut" style={{fontSize:12,color:'var(--c-text-3)'}}>{f.size}</span>
                      <Chip tone={f.tone} dot>{f.kindLabel}</Chip>
                    </div>
                    <div style={{fontSize:12.5,color:'var(--c-text-2)',marginBottom:2}}>判別: {f.detect}</div>
                    <div style={{fontSize:12.5,color:'var(--c-text-2)'}}>処理経路: <b style={{color:'var(--c-text)'}}>{f.route}</b></div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div className="cx-card pad" style={{marginTop:14,fontSize:12.5,color:'var(--c-text-2)',lineHeight:1.8}}>
            <b style={{color:'var(--c-text)'}}>判別のしくみ</b> — 拡張子と内容（PDFはテキストレイヤの有無）から種別を自動判別し、処理経路を選択します。
            テキスト埋め込みPDFは表構造をそのまま抽出できるため高精度、スキャンPDFは OCR を経由するため読取精度が下がり、結果は「要確認」として提示されます。
          </div>

          {phase==='files' ? (
            <div style={{display:'flex',gap:10,justifyContent:'flex-end',marginTop:16}}>
              <Btn kind="out" icon="upload" onClick={()=>setPhase('upload')}>ファイルを選び直す</Btn>
              <Btn icon="check" onClick={()=>{setPhase('running'); setTimeout(()=>{setTab('extract'); setPhase('done');},1800);}}>この内容で照合を開始</Btn>
            </div>
          ) : (
            <div className="cx-card pad" style={{marginTop:16}}>
              <div style={{fontSize:13.5,fontWeight:700,marginBottom:12,display:'flex',alignItems:'center',gap:10}}>
                <CXIcon name="refresh" size={18} color="var(--c-primary)"/>抽出・照合を実行中…（非同期処理・経路別に並行実行）
              </div>
              {d.pipelines.map(p=>(
                <div key={p.id} style={{marginBottom:12}}>
                  <div style={{fontSize:12.5,marginBottom:4}}><b>{p.label}</b><span className="mut" style={{color:'var(--c-text-3)',marginLeft:8}}>{p.desc}</span></div>
                  <div className="cx-bar"><i style={{width:p.width}}/></div>
                </div>
              ))}
            </div>
          )}
          <Disclaimer/>
        </div>
      </div>
    );
  }

  // ---- 2段階タブ（①抽出結果 → ②照合結果） ----
  const Tabs = () => (
    <div style={{display:'flex',gap:8,marginBottom:16}}>
      <Btn kind={tab==='extract'?'pri':'out'} size="sm" icon="file" onClick={()=>setTab('extract')}>① 抽出結果（ソース別）</Btn>
      <Btn kind={tab==='match'?'pri':'out'} size="sm" icon="check" onClick={()=>setTab('match')}>② 照合結果</Btn>
    </div>
  );

  const FileRow = () => (
    <div style={{display:'flex',alignItems:'center',gap:12,marginBottom:12,fontSize:12.5,flexWrap:'wrap'}}>
      {d.uploadFiles.map(f=>(
        <span key={f.id} style={{display:'inline-flex',alignItems:'center',gap:6}}>
          <CXIcon name={f.kind==='dwg'?'ruler':'file'} size={15} color="#656c87"/>
          <b>{f.name}</b>
          <Chip tone={f.tone} dot>{f.kindLabel}</Chip>
        </span>
      ))}
      <Chip tone="ok" dot>抽出完了</Chip>
    </div>
  );

  const ExtractCard = ({ title, icon, summary, columns, rows, renderRow, note }) => (
    <div className="cx-card" style={{overflow:'hidden'}}>
      <div className="cx-card-h">
        <h3 style={{display:'flex',alignItems:'center',gap:8}}><CXIcon name={icon} size={16}/>{title}</h3>
        <span className="hint">{summary.label}: <b>{summary.value}</b>（{summary.note}）</span>
      </div>
      <table className="cx-tbl">
        <thead><tr>{columns.map(c=><th key={c}>{c}</th>)}</tr></thead>
        <tbody>{rows.map(renderRow)}</tbody>
      </table>
      {note && <div style={{padding:'10px 16px',borderTop:'1px solid var(--c-border)',fontSize:12,color:'var(--c-text-2)'}}>{note}</div>}
    </div>
  );

  const extractBody = (
    <>
      <div className="cx-stats" style={{gridTemplateColumns:'repeat(3,1fr)',marginBottom:18}}>
        <Stat lab="平面図: 杭シンボル検出" icon="map" val="24" unit="本"/>
        <Stat lab="断面図: 寸法・旗揚げ抽出" icon="ruler" val="11/13" unit="項目"/>
        <Stat lab="数量表: 行抽出" icon="file" val="6/6" unit="行"/>
      </div>
      <div className="cx-grid2" style={{gridTemplateColumns:'1fr 1fr',alignItems:'start',marginBottom:16}}>
        <ExtractCard title="平面図からの抽出" icon="map" summary={d.extractPlan.summary}
          columns={['杭番号','座標X','座標Y','信頼度','判定']}
          rows={d.extractPlan.rows}
          renderRow={r=>(
            <tr key={r.id}>
              <td className="strong">{r.pile}</td><td>{r.x}</td><td>{r.y}</td><td className="mut">{r.conf}</td>
              <td><Chip tone={EXTRACT_STATE[r.state].tone} dot>{EXTRACT_STATE[r.state].label}</Chip></td>
            </tr>
          )}
          note="杭シンボル（円/ブロック）と杭番号ラベルをエンティティ解析で検出しています。"/>
        <ExtractCard title="断面図からの抽出 ★最難" icon="ruler" summary={d.extractSection.summary}
          columns={['杭番号','項目','抽出値','信頼度','判定']}
          rows={d.extractSection.rows}
          renderRow={r=>(
            <tr key={r.id}>
              <td className="strong">{r.pile}</td><td className="mut">{r.item}</td><td>{r.val}</td><td className="mut">{r.conf}</td>
              <td><Chip tone={EXTRACT_STATE[r.state].tone} dot>{EXTRACT_STATE[r.state].label}</Chip></td>
            </tr>
          )}
          note="寸法線・旗揚げ（引出線）を解析し、値を正しい杭に紐付けています。信頼度の低い項目は「要確認」として提示します。"/>
      </div>
      <ExtractCard title="数量表からの抽出" icon="file" summary={d.extractTable.summary}
        columns={['杭番号','項目','値','入力（処理経路）','信頼度','判定']}
        rows={d.extractTable.rows}
        renderRow={r=>(
          <tr key={r.id}>
            <td className="strong">{r.pile}</td><td className="mut">{r.item}</td><td>{r.val}</td>
            <td><Chip tone={r.src==='スキャンPDF'?'warn':'ok'} dot>{r.src}</Chip></td>
            <td className="mut">{r.conf}</td>
            <td><Chip tone={EXTRACT_STATE[r.state].tone} dot>{EXTRACT_STATE[r.state].label}</Chip></td>
          </tr>
        )}
        note="テキスト埋め込みPDFは表構造抽出（高精度）、スキャンPDFは OCR 経由（読取精度が下がるため要確認として提示）。径区分・単位は正規化済みです。"/>
      <div className="cx-card pad" style={{marginTop:16,display:'flex',alignItems:'center',gap:12,justifyContent:'space-between'}}>
        <div style={{fontSize:13,color:'var(--c-text-2)'}}>ソース別の抽出結果を確認したら、図面⇔数量表の照合結果へ進みます。</div>
        <Btn icon="check" onClick={()=>setTab('match')}>② 照合結果を確認</Btn>
      </div>
    </>
  );

  const matchBody = (
    <>
      <div className="cx-stats" style={{gridTemplateColumns:'repeat(4,1fr)',marginBottom:18}}>
        <Stat lab="不一致" icon="alert" val={counts.mismatch} unit="件"/>
        <Stat lab="欠落" icon="x" val={counts.missing} unit="件"/>
        <Stat lab="余剰" icon="plus" val={counts.surplus} unit="件"/>
        <Stat lab="一致" icon="check" val={counts.ok} unit="件"/>
      </div>
      <div className="cx-grid2" style={{gridTemplateColumns:'1fr 1fr',alignItems:'start'}}>
        {/* 結果一覧 */}
        <div className="cx-card" style={{overflow:'hidden'}}>
          <div className="cx-card-h"><h3>照合一覧</h3><span className="hint">行をクリックで図面上の該当箇所を表示</span></div>
          <table className="cx-tbl">
            <thead><tr><th>杭番号</th><th>項目</th><th>抽出元</th><th>図面</th><th>数量表</th><th>判定</th><th>人の確認</th></tr></thead>
            <tbody>
              {d.drawingResults.map(r=>(
                <tr key={r.id} onClick={()=>setActive(r)} style={active.id===r.id?{background:'var(--c-primary-bg)'}:undefined}>
                  <td className="strong">{r.pile}</td><td className="mut">{r.item}</td>
                  <td className="mut">{r.src}</td>
                  <td>{r.dwg}</td><td>{r.tbl}</td>
                  <td><Chip tone={STATE[r.state].tone} dot>{STATE[r.state].label}</Chip></td>
                  <td>{reviews[r.id]
                    ? <Chip tone={reviews[r.id].tone} dot>{reviews[r.id].tone==='ok'?'確認済':'差戻し'}</Chip>
                    : <Chip tone="muted">未確認</Chip>}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* 図面ビュー（ハイライト） */}
        <div className="cx-card" style={{overflow:'hidden'}}>
          <div className="cx-card-h"><h3>図面プレビュー</h3><span className="hint">{active.pile}・{active.item}（{active.src}）</span></div>
          <div style={{background:'#eef1f5',padding:24,display:'flex',justifyContent:'center'}}>
            <div style={{transform:'scale(.78)',transformOrigin:'top center'}}>
              <BlueprintPage>
                <div className={`cx-hl${active.state==='ok'?' ok':''}`}
                     style={{left:active.state==='ok'?'40%':'66%',top:'30%',width:'56px',height:'56px'}}>
                  <span className="tag">{active.pile} {STATE[active.state].label}</span>
                </div>
              </BlueprintPage>
            </div>
          </div>
          <div style={{padding:'12px 16px',borderTop:'1px solid var(--c-border)',fontSize:12.5,color:'var(--c-text-2)',lineHeight:1.7}}>
            断面図の寸法線・引出線を解析し、杭径・杭長・天端標高・根入れ深度を該当杭へ自動で紐付けています（モックでは模式表示）。差異の最終判断は担当者さまが行う候補提示型です。
          </div>
          {/* 判定に対する人の確認アクション */}
          <div style={{padding:'12px 16px',borderTop:'1px solid var(--c-border)'}}>
            {reviews[active.id] ? (
              <div style={{fontSize:12.5,display:'flex',alignItems:'center',gap:8}}>
                <CXIcon name={reviews[active.id].tone==='ok'?'check':'alert'} size={15} color={reviews[active.id].tone==='ok'?'#1c9d5a':'#d98a00'}/>
                <span><b>{reviews[active.id].by}</b> が {reviews[active.id].at} に記録: {reviews[active.id].action}</span>
              </div>
            ) : (
              <div style={{display:'flex',gap:8,alignItems:'center',justifyContent:'space-between',flexWrap:'wrap'}}>
                <span style={{fontSize:12.5,color:'var(--c-text-2)'}}>{active.pile}・{active.item} の判定「{STATE[active.state].label}」が正しいか、担当者の確認を記録します。</span>
                <span style={{display:'flex',gap:8}}>
                  <Btn size="sm" icon="check" onClick={()=>addReview(active,`判定「${STATE[active.state].label}」を確認`,'ok')}>判定を確認</Btn>
                  <Btn size="sm" kind="out" icon="x" onClick={()=>addReview(active,'差戻し（判定を再確認）','warn')}>差戻し</Btn>
                </span>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* 確認履歴 */}
      <div className="cx-card" style={{overflow:'hidden',marginTop:16}}>
        <div className="cx-card-h"><h3>確認履歴</h3><span className="hint">誰が・いつ・どの判定を確認/差戻ししたかの記録</span></div>
        <table className="cx-tbl">
          <thead><tr><th>日時</th><th>確認者</th><th>対象</th><th>アクション</th></tr></thead>
          <tbody>
            {reviewLog.map(l=>(
              <tr key={l.id}>
                <td className="mut">{l.at}</td><td>{l.by}</td><td className="strong">{l.target}</td>
                <td><Chip tone={l.tone} dot>{l.action}</Chip></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );

  return (
    <div className="cx-main">
      <PageHeader crumb="ポータル / 図面数量照査" title="照査結果" onBack={onBack}
        actions={<>
          <Chip tone="warn">PoC</Chip>
          <Btn kind="out" icon="upload" size="sm" onClick={()=>setPhase('upload')}>別の図面</Btn>
          <Btn icon="download" onClick={()=>notify('サンプルのためCSV出力はイメージです')}>CSV出力</Btn>
        </>}/>
      <PocBanner/>
      <FileRow/>
      <Tabs/>
      {tab==='extract' ? extractBody : matchBody}
      <Disclaimer/>
    </div>
  );
};
window.ThemeDrawing = ThemeDrawing;
