// Extra screens — ZHSR02-13 checklist, Nonconformity, Template wizard, Drive settings, Plot registry

const D3 = window.NMYTL_DATA;

// ============ ZHSR02-13 — 巨型查核表 ============
const ChecklistScreen = ({ caseData, completion, onBack }) => {
  const [activeChapter, setActiveChapter] = React.useState(D3.checklistChapters[0].id);
  const [answers, setAnswers] = React.useState(() => {
    // Pre-fill based on completion state
    const base = {};
    if (completion === 'empty') return base;
    D3.checklistChapters.forEach((ch) => {
      const factor = completion === 'half' ? 0.5 : 1;
      const items = ch.items || makeStubItems(ch);
      items.slice(0, Math.floor(items.length * factor)).forEach((it) => {
        base[it.id] = it.answer || ['符合', '符合', '符合', '不適用', '不符合'][Math.floor(Math.random() * 5)];
      });
    });
    return base;
  });

  const totalItems = D3.checklistChapters.reduce((s, ch) => s + ch.count, 0);
  const totalDone = Object.keys(answers).length;
  const overallPct = (totalDone / totalItems) * 100;

  const ch = D3.checklistChapters.find((c) => c.id === activeChapter);
  const items = ch.items || makeStubItems(ch);

  return (
    <div className="col" style={{ flex: 1, minHeight: 0 }}>
      {/* Header */}
      <div style={{ padding: '16px 28px', borderBottom: '1px solid var(--line)', background: 'var(--surface)' }}>
        <div className="row gap-8 text-xs text-muted mb-8">
          <button className="btn btn-ghost btn-sm" onClick={onBack}>
            <Icon name="arrow_left" size={12} />{caseData.operatorName}
          </button>
          <span>/</span>
          <span>ZHSR02-13</span>
        </div>
        <div className="row" style={{ justifyContent: 'space-between' }}>
          <div>
            <div className="text-2xl font-semibold">生產出貨查核表 ZHSR02-13</div>
            <div className="text-xs text-muted text-mono mt-4">
              Rev6.0 · 2025-03-07 生效 · 預估完成時間 35-50 分鐘
            </div>
          </div>
          <div className="row gap-12" style={{ alignItems: 'center' }}>
            <div style={{ textAlign: 'right' }}>
              <div className="text-xs text-muted">整體完成度</div>
              <div className="text-lg font-bold text-mono">{totalDone} / {totalItems} ({Math.floor(overallPct)}%)</div>
            </div>
            <div style={{ width: 200 }}>
              <div className="progress" style={{ height: 8 }}>
                <div className="progress-fill" style={{
                  width: `${overallPct}%`,
                  background: overallPct === 100 ? 'var(--ok)' : 'var(--gold)',
                }} />
              </div>
            </div>
            <button className="btn"><Icon name="save" size={13} />儲存草稿</button>
            <button className="btn btn-primary"><Icon name="download" size={13} />匯出 .docx</button>
          </div>
        </div>
      </div>

      <div className="row" style={{ flex: 1, minHeight: 0, overflow: 'hidden' }}>
        {/* Chapter sidebar */}
        <div style={{ width: 240, flexShrink: 0, borderRight: '1px solid var(--line)',
                       background: 'var(--surface)', overflowY: 'auto' }}>
          <div style={{ padding: '14px 16px 8px' }}>
            <div className="text-xs font-semibold text-muted" style={{ textTransform: 'uppercase', letterSpacing: '.06em' }}>
              章節 · {D3.checklistChapters.length}
            </div>
          </div>
          {D3.checklistChapters.map((ch, i) => {
            const factor = completion === 'empty' ? 0 : completion === 'half' ? 0.5 : 1;
            const done = Math.floor(ch.count * factor);
            const pct = (done / ch.count) * 100;
            return (
              <button key={ch.id} className="nav-item" data-active={activeChapter === ch.id}
                      onClick={() => setActiveChapter(ch.id)}
                      style={{ padding: '10px 14px', alignItems: 'flex-start' }}>
                <div style={{ flex: 1 }}>
                  <div className="row" style={{ justifyContent: 'space-between' }}>
                    <span className="text-xs text-mono text-muted">第 {i + 1} 章</span>
                    <span className="text-xs text-mono" style={{
                      color: pct === 100 ? 'var(--ok)' : pct > 0 ? 'var(--gold)' : 'var(--ink-3)',
                    }}>{done}/{ch.count}</span>
                  </div>
                  <div className="text-sm font-medium" style={{ marginTop: 2 }}>{ch.title}</div>
                  <div className="progress mt-4" style={{ height: 3 }}>
                    <div className="progress-fill" style={{
                      width: `${pct}%`,
                      background: pct === 100 ? 'var(--ok)' : pct > 0 ? 'var(--gold)' : 'var(--line-2)',
                    }} />
                  </div>
                </div>
              </button>
            );
          })}
        </div>

        {/* Item list */}
        <div className="main" style={{ padding: 28 }}>
          <div className="row" style={{ justifyContent: 'space-between', marginBottom: 16 }}>
            <div>
              <div className="text-xl font-semibold">{ch.title}</div>
              <div className="text-xs text-muted mt-4">
                共 {ch.count} 項 · ★★ 重點題 6 項
              </div>
            </div>
            <div className="row gap-6">
              <button className="btn btn-sm"><Icon name="filter" size={12} />未填</button>
              <button className="btn btn-sm"><Icon name="warn" size={12} />不符合</button>
            </div>
          </div>

          {items.map((it, idx) => {
            const ans = answers[it.id];
            return (
              <div key={it.id} className="card mb-12" style={{
                borderColor: ans === '不符合' ? 'color-mix(in srgb, var(--err) 30%, var(--line))' : 'var(--line)',
                background: ans === '不符合' ? 'color-mix(in srgb, var(--err) 4%, var(--surface))' : 'var(--surface)',
              }}>
                <div className="row gap-12" style={{ alignItems: 'flex-start' }}>
                  <div className="text-sm text-mono text-muted" style={{ width: 56, flexShrink: 0, paddingTop: 2 }}>
                    {ch.id}-{String(idx + 1).padStart(2, '0')}
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="row gap-8" style={{ alignItems: 'flex-start' }}>
                      <div className="text-md" style={{ flex: 1, fontWeight: 500 }}>{it.q}</div>
                      {it.priority === 2 && (
                        <span className="status" style={{ color: 'var(--err)', borderColor: 'color-mix(in srgb, var(--err) 30%, var(--line))' }}>
                          ★★
                        </span>
                      )}
                      {it.priority === 1 && (
                        <span className="status" style={{ color: 'var(--gold)' }}>★</span>
                      )}
                      <span className="text-xs text-muted">頻率 · {it.freq}</span>
                    </div>
                    <div className="triple mt-12" style={{ maxWidth: 560 }}>
                      {['符合', '不符合', '不適用'].map((opt) => (
                        <button key={opt} data-on={ans === opt ? opt : undefined}
                                onClick={() => setAnswers({ ...answers, [it.id]: opt })}>
                          {ans === opt && <Icon name="check" size={14} />}
                          {opt}
                        </button>
                      ))}
                    </div>
                    {ans === '不符合' && (
                      <div className="fade-in mt-12">
                        <label className="label">不符合說明 (必填)</label>
                        <textarea className="textarea" rows={2}
                                  placeholder="請說明不符合的事實、證據與佐證..." />
                      </div>
                    )}
                  </div>
                </div>
              </div>
            );
          })}

          <div className="row" style={{ justifyContent: 'space-between', marginTop: 24 }}>
            <button className="btn"><Icon name="chevron_left" size={13} />上一章</button>
            <div className="text-xs text-muted">
              本章節 · {items.filter((it) => answers[it.id]).length} / {items.length} 已填
            </div>
            <button className="btn btn-primary">下一章<Icon name="chevron_right" size={13} /></button>
          </div>
        </div>
      </div>
    </div>
  );
};

const makeStubItems = (ch) => {
  // Stub questions for chapters without explicit items
  const samples = {
    farm: ['農場是否設置適當的緩衝帶？', '是否張貼禁止外人進入告示？', '是否有完整的農場平面圖？',
           '農具是否定期清潔消毒？', '是否實施輪作或合理輪作計畫？'],
    soil: ['是否定期檢測土壤重金屬？', '灌溉水源是否符合農田用水標準？',
           '土壤改良劑使用是否有紀錄？', '是否使用合格肥料？'],
    fert: ['肥料是否儲存於專用空間？', '化學肥料與有機肥料是否分區存放？',
           '是否保存施肥紀錄？', '混合肥料是否依配方比例？'],
    pest: ['農藥儲存是否上鎖管理？', '農藥是否在效期內？',
           '農藥使用是否依許可期間與用量？', '空農藥瓶是否分類回收？',
           '是否實施綜合管理 IPM？', '田間是否觀察病蟲害動態？'],
    harv: ['採收工具是否清潔消毒？', '採收作業是否避免污染？',
           '採收後是否立即降溫？', '採收人員是否有衛生訓練？'],
    post: ['採後處理場所是否符合衛生規範？', '冷藏設備溫度是否監控？',
           '加工區是否分區管理？', '是否使用合格包材？'],
    pack: ['包裝場所是否符合 GHP？', '包裝材料是否符合食品接觸標準？',
           '出貨前是否進行品管檢查？', '溫控車輛溫度紀錄是否完整？'],
    trace: ['履歷紀錄是否完整保留 5 年？', '產品是否標示可溯源 QR code？',
            '是否定期核對庫存與紀錄？', '出貨對象資訊是否完整？'],
  };
  const list = samples[ch.id] || ['測試題目 A', '測試題目 B'];
  const out = [];
  for (let i = 0; i < ch.count; i++) {
    out.push({
      id: `${ch.id}-${i + 1}`,
      q: list[i % list.length],
      priority: i % 7 === 0 ? 2 : i % 4 === 0 ? 1 : 0,
      freq: ['隨時', '年度', '每批次', '半年'][i % 4],
    });
  }
  return out;
};

// ============ Non-conformity (動態多列表格) ============
const NonconformityScreen = ({ caseData, completion, onBack }) => {
  const [items, setItems] = React.useState(() => {
    if (completion === 'empty') return [];
    if (completion === 'half') return D3.nonconformities.slice(0, 1);
    return [...D3.nonconformities];
  });
  const [expanded, setExpanded] = React.useState(items[0]?.id);

  const addRow = () => {
    const newItem = {
      id: `n${Date.now()}`,
      clause: '',
      fact: '',
      severity: '輕微',
      status: '待改善',
      dueDate: '',
    };
    setItems([...items, newItem]);
    setExpanded(newItem.id);
  };

  const updateItem = (id, patch) => {
    setItems(items.map((it) => it.id === id ? { ...it, ...patch } : it));
  };

  const removeItem = (id) => setItems(items.filter((it) => it.id !== id));

  return (
    <div className="col" style={{ flex: 1, minHeight: 0 }}>
      <div style={{ padding: '16px 28px', borderBottom: '1px solid var(--line)', background: 'var(--surface)' }}>
        <div className="row gap-8 text-xs text-muted mb-8">
          <button className="btn btn-ghost btn-sm" onClick={onBack}>
            <Icon name="arrow_left" size={12} />{caseData.operatorName}
          </button>
          <span>/</span>
          <span>ZHSR02-8 · 不符合項報告</span>
        </div>
        <div className="row" style={{ justifyContent: 'space-between' }}>
          <div>
            <div className="text-2xl font-semibold">不符合項報告</div>
            <div className="text-xs text-muted mt-4">
              {items.length} 筆 · 主要 {items.filter((i) => i.severity === '主要').length} ·
              輕微 {items.filter((i) => i.severity === '輕微').length}
            </div>
          </div>
          <div className="row gap-8">
            <button className="btn"><Icon name="save" size={13} />儲存</button>
            <button className="btn btn-primary"><Icon name="download" size={13} />匯出 .docx</button>
          </div>
        </div>
      </div>

      <div className="main" style={{ padding: 28 }}>
        <div className="row" style={{ justifyContent: 'space-between', marginBottom: 16 }}>
          <div className="text-md font-semibold">不符合項清單</div>
          <button className="btn btn-primary" onClick={addRow}>
            <Icon name="plus" size={13} />新增不符合項
          </button>
        </div>

        {items.length === 0 && (
          <div className="card" style={{ textAlign: 'center', padding: 40 }}>
            <Icon name="check" size={36} style={{ color: 'var(--ok)', opacity: .8 }} />
            <div className="text-md mt-12 font-semibold">無不符合項</div>
            <div className="text-sm text-muted mt-4">
              本次稽核所有查核項皆「符合」或「不適用」
            </div>
            <button className="btn mt-16" onClick={addRow}>仍要新增不符合項</button>
          </div>
        )}

        {items.map((it, idx) => (
          <div key={it.id} className="card mb-12" style={{
            borderColor: it.severity === '主要' ? 'color-mix(in srgb, var(--err) 30%, var(--line))' : 'var(--line)',
            padding: 0, overflow: 'hidden',
          }}>
            <div className="row" style={{ padding: '12px 16px', cursor: 'pointer',
                                            background: expanded === it.id ? 'var(--surface-2)' : 'transparent',
                                            borderBottom: expanded === it.id ? '1px solid var(--line)' : 'none' }}
                 onClick={() => setExpanded(expanded === it.id ? null : it.id)}>
              <div className="row gap-10" style={{ flex: 1, alignItems: 'center' }}>
                <Icon name={expanded === it.id ? 'chevron_down' : 'chevron_right'} size={14} />
                <div className="text-sm text-mono text-muted">{String(idx + 1).padStart(2, '0')}</div>
                <div className="text-sm text-mono font-medium" style={{ minWidth: 60 }}>
                  {it.clause || <span className="text-muted">無條款</span>}
                </div>
                <div className="text-sm" style={{ flex: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                  {it.fact || <span className="text-muted">點此填寫事實...</span>}
                </div>
              </div>
              <div className="row gap-8">
                <span className="status" style={{
                  color: it.severity === '主要' ? 'var(--err)' : 'var(--gold)',
                }}><span className="dot" />{it.severity}</span>
                <button className="btn btn-sm btn-ghost btn-danger"
                        onClick={(e) => { e.stopPropagation(); removeItem(it.id); }}>
                  <Icon name="trash" size={12} />
                </button>
              </div>
            </div>
            {expanded === it.id && (
              <div className="fade-in" style={{ padding: 16 }}>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 12, marginBottom: 12 }}>
                  <div>
                    <label className="label">不符合條款</label>
                    <input className="input" placeholder="例：4.2.1" value={it.clause}
                           onChange={(e) => updateItem(it.id, { clause: e.target.value })}
                           style={{ fontFamily: 'var(--font-mono)' }} />
                  </div>
                  <div>
                    <label className="label">嚴重度</label>
                    <div className="row gap-4">
                      {['輕微', '主要', '嚴重'].map((sev) => (
                        <button key={sev} className="btn btn-sm" style={{ flex: 1 }}
                                onClick={() => updateItem(it.id, { severity: sev })}
                                data-active={it.severity === sev}
                                style2={{
                                  background: it.severity === sev ? 'var(--ink)' : 'var(--surface)',
                                  color: it.severity === sev ? 'var(--surface)' : 'var(--ink-2)',
                                }}>
                          {sev}
                        </button>
                      ))}
                    </div>
                  </div>
                  <div style={{ gridColumn: '1 / -1' }}>
                    <label className="label">事實描述</label>
                    <textarea className="textarea" rows={3} value={it.fact}
                              onChange={(e) => updateItem(it.id, { fact: e.target.value })}
                              placeholder="客觀描述觀察到的事實、提供的佐證..." />
                  </div>
                  <div>
                    <label className="label">改善期限</label>
                    <input className="input" type="date" value={it.dueDate}
                           onChange={(e) => updateItem(it.id, { dueDate: e.target.value })} />
                  </div>
                  <div>
                    <label className="label">關閉狀態</label>
                    <select className="select" value={it.status}
                            onChange={(e) => updateItem(it.id, { status: e.target.value })}>
                      <option>待改善</option>
                      <option>改善中</option>
                      <option>已關閉</option>
                    </select>
                  </div>
                  <div style={{ gridColumn: '1 / -1' }}>
                    <label className="label">改善計畫 / 證據</label>
                    <textarea className="textarea" rows={2}
                              placeholder="經營者提出的改善作法,以及驗證機構接受的依據..." />
                  </div>
                </div>
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
};

// ============ Plot registry ============
const PlotRegistryScreen = () => {
  const plots = [
    { op: '張朝安', name: '嘉興段', no: '0526-0023', area: 0.5234, va: 0.5234, code: '01', crop: '水稻 / 香米', town: '嘉義縣大林鎮' },
    { op: '張朝安', name: '嘉興段', no: '0526-0024', area: 0.3812, va: 0.3812, code: '01', crop: '水稻 / 香米', town: '嘉義縣大林鎮' },
    { op: '張朝安', name: '嘉興段', no: '0526-0031', area: 0.2156, va: 0.2156, code: '04', crop: '採後處理場', town: '嘉義縣大林鎮' },
    { op: '張朝安', name: '嘉興段', no: '0526-0045', area: 0.4188, va: 0.4188, code: '01', crop: '水稻 / 香米', town: '嘉義縣大林鎮' },
    { op: '陳錦桂', name: '名間段', no: '0152-0019', area: 0.6720, va: 0.6720, code: '01', crop: '茶葉', town: '南投縣名間鄉' },
    { op: '陳錦桂', name: '名間段', no: '0152-0021', area: 0.4520, va: 0.4520, code: '01', crop: '茶葉', town: '南投縣名間鄉' },
    { op: '黃秀蘭', name: '鹿谷段', no: '0834-0102', area: 0.8234, va: 0.8234, code: '01', crop: '茶葉', town: '南投縣鹿谷鄉' },
    { op: '李建民', name: '東勢段', no: '0421-0056', area: 0.5432, va: 0.5432, code: '02', crop: '梨', town: '台中市東勢區' },
  ];
  return (
    <div style={{ padding: 28 }}>
      <div className="row" style={{ justifyContent: 'space-between', marginBottom: 16 }}>
        <div>
          <div className="text-2xl font-semibold">農地清冊</div>
          <div className="text-sm text-muted mt-4">{plots.length} 筆 · 共 {plots.reduce((s, p) => s + p.area, 0).toFixed(2)} ha</div>
        </div>
        <div className="row gap-8">
          <button className="btn"><Icon name="upload" size={13} />從 Excel 匯入</button>
          <button className="btn btn-primary"><Icon name="plus" size={13} />新增地號</button>
        </div>
      </div>

      <div className="row gap-8 mb-16">
        <div className="row gap-6 card" style={{ padding: '4px 8px', flex: 1 }}>
          <Icon name="search" size={14} style={{ color: 'var(--ink-3)' }} />
          <input className="input" placeholder="搜尋縣市 / 鄉鎮 / 地段名 / 地號..."
                 style={{ border: 'none', padding: 0, background: 'transparent' }} />
        </div>
        <select className="select" style={{ width: 160 }}><option>所有經營者</option></select>
        <select className="select" style={{ width: 160 }}><option>所有面積認定碼</option></select>
      </div>

      <div className="card-flat" style={{ padding: 0, overflow: 'hidden' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '60px 1fr 1fr 1fr 1fr 100px 100px 80px',
                       padding: '12px 16px', borderBottom: '1px solid var(--line)',
                       fontSize: 11, fontWeight: 600, color: 'var(--ink-3)',
                       textTransform: 'uppercase', letterSpacing: '.04em' }}>
          <div></div><div>經營者</div><div>地段名 / 地號</div><div>鄉鎮</div>
          <div>作物</div><div>面積</div><div>面積碼</div><div></div>
        </div>
        {plots.map((p, i) => (
          <div key={i} style={{
            display: 'grid', gridTemplateColumns: '60px 1fr 1fr 1fr 1fr 100px 100px 80px',
            padding: '12px 16px', borderBottom: '1px solid var(--line)',
            alignItems: 'center',
          }}>
            <div style={{ width: 36, height: 36, borderRadius: 4, overflow: 'hidden' }}>
              <SatelliteSVG seed={i * 7 + 3} label="" area="" />
            </div>
            <div className="text-sm font-medium">{p.op}</div>
            <div>
              <div className="text-sm font-medium">{p.name} {p.no}</div>
            </div>
            <div className="text-sm">{p.town}</div>
            <div className="text-sm">{p.crop}</div>
            <div className="text-sm text-mono">{p.area.toFixed(4)}</div>
            <div className="text-sm text-mono">{p.code}</div>
            <div className="row gap-4">
              <button className="btn btn-sm btn-ghost"><Icon name="edit" size={11} /></button>
              <button className="btn btn-sm btn-ghost"><Icon name="more" size={11} /></button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

// ============ Template wizard ============
const TemplateScreen = () => {
  const [showWizard, setShowWizard] = React.useState(false);
  return (
    <div style={{ padding: 28 }}>
      <div className="row" style={{ justifyContent: 'space-between', marginBottom: 16 }}>
        <div>
          <div className="text-2xl font-semibold">樣板管理</div>
          <div className="text-sm text-muted mt-4">6 份政府指定樣板 · 由管理員維護版本</div>
        </div>
        <button className="btn btn-primary" onClick={() => setShowWizard(true)}>
          <Icon name="upload" size={13} />上傳新版
        </button>
      </div>

      {showWizard && <TemplateWizard onClose={() => setShowWizard(false)} />}

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 16 }}>
        {D3.templates.map((t) => (
          <div key={t.id} className="card">
            <div className="row" style={{ justifyContent: 'space-between' }}>
              <div className="row gap-10">
                <div style={{ width: 40, height: 50, background: 'var(--surface-2)',
                              border: '1px solid var(--line)', borderRadius: 4,
                              display: 'flex', alignItems: 'center', justifyContent: 'center',
                              color: 'var(--ink-3)' }}>
                  <Icon name="file" size={18} />
                </div>
                <div>
                  <div className="text-sm text-mono text-muted">{t.id}</div>
                  <div className="text-md font-semibold">{t.name}</div>
                </div>
              </div>
              <span className="status" data-status="approved"><span className="dot" />生效中</span>
            </div>
            <div className="divider" />
            <div className="row" style={{ justifyContent: 'space-between' }}>
              <div className="text-xs text-muted">
                <div className="kv"><span className="k">版本</span><span className="v text-mono">{t.version}</span></div>
                <div className="kv"><span className="k">生效日</span><span className="v text-mono">{t.date}</span></div>
                <div className="kv"><span className="k">欄位數</span><span className="v text-mono">{t.fields}</span></div>
              </div>
              <div className="col gap-6">
                <button className="btn btn-sm"><Icon name="download" size={11} />下載</button>
                <button className="btn btn-sm btn-ghost"><Icon name="upload" size={11} />更新</button>
                <button className="btn btn-sm btn-ghost"><Icon name="more" size={11} />歷史</button>
              </div>
            </div>
            {t.difficulty === 'hard' && (
              <div style={{ marginTop: 8, padding: 8, borderRadius: 4,
                            background: 'color-mix(in srgb, var(--gold) 12%, var(--surface))',
                            fontSize: 11, color: 'var(--ink-2)' }}>
                ⚠️ 此樣板含 230+ 欄位,建議在桌面版逐章填寫
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
};

const TemplateWizard = ({ onClose }) => {
  const [step, setStep] = React.useState(1);
  const steps = [
    { id: 1, label: '上傳檔案' },
    { id: 2, label: '解析 schema' },
    { id: 3, label: 'Diff 比對' },
    { id: 4, label: '校稿' },
    { id: 5, label: '試填驗證' },
    { id: 6, label: '發布' },
  ];

  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(20, 18, 14, .55)',
      zIndex: 100, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24,
    }}>
      <div className="card" style={{ width: 720, maxHeight: '90vh', display: 'flex',
                                       flexDirection: 'column', padding: 0, overflow: 'hidden' }}>
        <div className="row" style={{ padding: '14px 20px', borderBottom: '1px solid var(--line)',
                                        justifyContent: 'space-between' }}>
          <div className="text-md font-semibold">上傳新版樣板 · ZHSR02-13</div>
          <button className="btn btn-ghost btn-sm" onClick={onClose}><Icon name="cross" size={14} /></button>
        </div>

        {/* Stepper */}
        <div className="row" style={{ padding: '14px 20px', borderBottom: '1px solid var(--line)', gap: 4 }}>
          {steps.map((s, i) => (
            <React.Fragment key={s.id}>
              <div className="row gap-6" style={{
                color: step >= s.id ? 'var(--accent)' : 'var(--ink-3)',
                fontWeight: step === s.id ? 600 : 400,
              }}>
                <div style={{
                  width: 22, height: 22, borderRadius: 11,
                  background: step > s.id ? 'var(--accent)' : step === s.id ? 'var(--accent)' : 'var(--surface-2)',
                  color: step >= s.id ? 'var(--accent-fg)' : 'var(--ink-3)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 11, fontWeight: 600, fontFamily: 'var(--font-mono)',
                }}>{step > s.id ? '✓' : s.id}</div>
                <span className="text-xs">{s.label}</span>
              </div>
              {i < steps.length - 1 && (
                <div style={{ flex: 1, height: 1, background: 'var(--line)', alignSelf: 'center' }} />
              )}
            </React.Fragment>
          ))}
        </div>

        <div style={{ flex: 1, overflowY: 'auto', padding: 20 }}>
          {step === 1 && (
            <div>
              <div className="text-md font-semibold mb-8">上傳 .docx 樣板</div>
              <div className="text-sm text-muted mb-16">必須是 .docx — 若是 .doc 請先用 Word 另存新檔</div>
              <div style={{
                border: '1.5px dashed var(--line-2)', borderRadius: 'var(--radius-lg)',
                padding: 40, textAlign: 'center', background: 'var(--surface-2)',
              }}>
                <Icon name="upload" size={32} style={{ color: 'var(--ink-3)', opacity: .6 }} />
                <div className="text-md mt-12 font-medium">將檔案拖入此處 或 點擊選擇</div>
                <div className="text-xs text-muted mt-4">支援 .docx · 最大 10MB</div>
                <div className="row gap-8 mt-16" style={{ justifyContent: 'center' }}>
                  <button className="btn">瀏覽檔案</button>
                  <button className="btn btn-ghost">查看樣板撰寫指南</button>
                </div>
              </div>
              <div className="card mt-16" style={{
                background: 'color-mix(in srgb, var(--gold) 8%, var(--surface))',
                borderColor: 'color-mix(in srgb, var(--gold) 25%, var(--line))',
              }}>
                <div className="text-sm font-semibold mb-4">⚠️ 上傳前須完成的前置作業</div>
                <ul style={{ margin: 0, paddingLeft: 20, fontSize: 12, color: 'var(--ink-2)' }}>
                  <li>把 FORMCHECKBOX、FORMTEXT 替換成 <code className="text-mono">{`{{ field_name }}`}</code></li>
                  <li>多列表格用 <code className="text-mono">{`{%tr for row in items %}...{%/tr%}`}</code> 包起</li>
                  <li>檢查中文字體一致性 (標楷體 12pt / 新細明體)</li>
                </ul>
              </div>
            </div>
          )}
          {step === 2 && (
            <div>
              <div className="text-md font-semibold mb-12">解析中</div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 12 }}>
                {[
                  { k: '抽取 placeholder 變數', v: '237 個', done: true },
                  { k: '識別 table loops', v: '4 個 (其中 1 個為不符合項清單)', done: true },
                  { k: '推測欄位型別', v: '單選 198 / 文字 24 / 日期 8 / 表格 4', done: true },
                  { k: '產生 schema 草案', v: '完成', done: true },
                ].map((row) => (
                  <div key={row.k} className="card" style={{ padding: 12 }}>
                    <div className="row gap-8">
                      <Icon name={row.done ? 'check' : 'sync'} size={14}
                            style={{ color: row.done ? 'var(--ok)' : 'var(--info)' }} />
                      <div className="text-xs font-medium">{row.k}</div>
                    </div>
                    <div className="text-md font-semibold mt-4 text-mono">{row.v}</div>
                  </div>
                ))}
              </div>
            </div>
          )}
          {step === 3 && (
            <div>
              <div className="text-md font-semibold mb-12">與當前版本 Rev6.0 的差異</div>
              <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
                {[
                  { type: 'add', label: '新增 12 個欄位', sub: '主要在「採後處理」章節' },
                  { type: 'remove', label: '移除 3 個欄位', sub: '原 c4 (產銷履歷標章相關) 整合至 c2' },
                  { type: 'change', label: '欄位類型變更 5 個', sub: '由文字改為三選一' },
                  { type: 'rename', label: '欄位重新命名 8 個', sub: '統一用詞,如 "農場" → "生產場域"' },
                ].map((d, i) => (
                  <div key={i} style={{
                    padding: '12px 16px',
                    borderTop: i ? '1px solid var(--line)' : 'none',
                  }}>
                    <div className="row gap-8">
                      <div style={{
                        width: 18, height: 18, borderRadius: 9,
                        background: d.type === 'add' ? 'var(--ok)' : d.type === 'remove' ? 'var(--err)' : 'var(--info)',
                        color: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center',
                        fontSize: 11, fontWeight: 700,
                      }}>{d.type === 'add' ? '+' : d.type === 'remove' ? '−' : '≠'}</div>
                      <div style={{ flex: 1 }}>
                        <div className="text-sm font-medium">{d.label}</div>
                        <div className="text-xs text-muted">{d.sub}</div>
                      </div>
                      <button className="btn btn-sm btn-ghost">查看</button>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
          {step >= 4 && (
            <div>
              <div className="text-md font-semibold mb-12">
                {step === 4 ? '人工校稿 schema (摘錄)' : step === 5 ? '試填驗證' : '發布'}
              </div>
              <pre style={{
                background: 'var(--surface-2)', padding: 16, borderRadius: 6,
                fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--ink-2)',
                overflowX: 'auto', maxHeight: 300,
              }}>{`template_id: ZHSR02-13
template_version: Rev7.0
title: 產銷履歷生產及出貨作業查核表
sections:
  - id: common
    title: 1. 共通事項
    items:
      - id: c1
        question: 經營者是否取得驗證機構合約?
        type: triple_state
        priority: 2
        frequency: 隨時
      - id: c2
        question: 是否設置內部稽核制度?
        type: triple_state
        ...
tables:
  - id: nonconformities
    columns: [序號, 條款, 事實, 嚴重度, 限期, 狀態]
    min_rows: 0`}</pre>
            </div>
          )}
        </div>

        <div className="row" style={{ padding: '14px 20px', borderTop: '1px solid var(--line)',
                                        justifyContent: 'space-between' }}>
          <button className="btn btn-ghost" onClick={onClose}>取消</button>
          <div className="row gap-8">
            {step > 1 && <button className="btn" onClick={() => setStep(step - 1)}>上一步</button>}
            {step < 6 ? (
              <button className="btn btn-primary" onClick={() => setStep(step + 1)}>
                下一步<Icon name="chevron_right" size={13} />
              </button>
            ) : (
              <button className="btn btn-primary" onClick={onClose}>
                發布為 Rev7.0<Icon name="check" size={13} />
              </button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

// ============ Drive Settings ============
const DriveScreen = () => {
  return (
    <div style={{ padding: 28 }}>
      <div className="row" style={{ justifyContent: 'space-between', marginBottom: 16 }}>
        <div>
          <div className="text-2xl font-semibold">雲端儲存 · Google Drive</div>
          <div className="text-sm text-muted mt-4">純檔案儲存桶角色 · 不使用 Docs / Sheets API</div>
        </div>
        <button className="btn"><Icon name="settings" size={13} />進階設定</button>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 16 }}>
        <div>
          <div className="card mb-16">
            <div className="row" style={{ justifyContent: 'space-between' }}>
              <div className="row gap-10">
                <div style={{ width: 40, height: 40, borderRadius: 8,
                              background: 'color-mix(in srgb, var(--ok) 15%, var(--surface))',
                              color: 'var(--ok)',
                              display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <Icon name="cloud_check" size={20} />
                </div>
                <div>
                  <div className="text-md font-semibold">已連線</div>
                  <div className="text-xs text-muted text-mono">最後同步 {D3.driveStats.lastSync}</div>
                </div>
              </div>
              <button className="btn btn-sm"><Icon name="sync" size={12} />立即同步</button>
            </div>
            <div className="divider" />
            <div className="kv"><span className="k">部署模式</span><span className="v">個人帳號 + Service Account (方案 A)</span></div>
            <div className="kv"><span className="k">Service Account</span>
              <span className="v text-mono text-xs">{D3.driveStats.serviceAccount}</span></div>
            <div className="kv"><span className="k">Scope</span><span className="v text-mono">drive (full access)</span></div>
            <div className="kv"><span className="k">Access token cache</span><span className="v">KV · 期限 3500s</span></div>
          </div>

          <div className="card mb-16">
            <div className="text-md font-semibold mb-12">配額用量</div>
            <div className="row" style={{ justifyContent: 'space-between', marginBottom: 8 }}>
              <span className="text-sm">{D3.driveStats.used} GB / {D3.driveStats.total} GB</span>
              <span className="text-xs text-muted">下次升級 NT$60 / 月 (200GB)</span>
            </div>
            <div className="progress" style={{ height: 8 }}>
              <div className="progress-fill" style={{ width: `${D3.driveStats.used / D3.driveStats.total * 100}%` }} />
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginTop: 16 }}>
              {[
                { label: '案件檔案', val: '1.78 GB', sub: '1,089 個檔' },
                { label: '樣板原檔', val: '12 MB', sub: '6 份 × 版本' },
                { label: '匯出文件', val: '320 MB', sub: '146 份' },
                { label: '系統備份', val: '24 MB', sub: 'D1 dump' },
              ].map((s) => (
                <div key={s.label}>
                  <div className="text-xs text-muted">{s.label}</div>
                  <div className="text-md font-semibold text-mono mt-4">{s.val}</div>
                  <div className="text-xs text-muted">{s.sub}</div>
                </div>
              ))}
            </div>
          </div>

          <div className="card">
            <div className="text-md font-semibold mb-12">資料夾結構</div>
            <pre className="text-mono text-sm" style={{
              background: 'var(--surface-2)', padding: 14, borderRadius: 6,
              color: 'var(--ink-2)', overflowX: 'auto', margin: 0,
            }}>{`📁 NMYTL
├─ 📁 cases/
│   └─ 📁 CASE-2026-0042/
│       ├─ 📁 photos/section-01/
│       ├─ 📁 exports/
│       └─ 📁 attachments/
├─ 📁 templates/
│   └─ 📁 ZHSR02-13-Rev6/
├─ 📁 plot-registry/
└─ 📁 system/`}</pre>
          </div>
        </div>

        <div>
          <div className="card mb-16">
            <div className="text-md font-semibold mb-12">健康狀態</div>
            {[
              { k: 'API quota (q/s)', v: '12 / 1000', ok: true },
              { k: 'OAuth token', v: '有效 (剩 41 分)', ok: true },
              { k: '上傳成功率', v: '99.8%', ok: true },
              { k: '平均上傳時間', v: '1.2 s / file', ok: true },
            ].map((row) => (
              <div key={row.k} className="row" style={{ padding: '6px 0',
                justifyContent: 'space-between', borderTop: '1px solid var(--line)' }}>
                <div className="row gap-6">
                  <Icon name="check" size={11} style={{ color: 'var(--ok)' }} />
                  <span className="text-xs">{row.k}</span>
                </div>
                <span className="text-xs text-mono">{row.v}</span>
              </div>
            ))}
          </div>

          <div className="card">
            <div className="text-md font-semibold mb-12">最近上傳</div>
            {[
              { f: 'satellite-001.jpg', case: 'CASE-2026-0042', t: '2 分前' },
              { f: 'photo-014.jpg', case: 'CASE-2026-0042', t: '4 分前' },
              { f: 'ZHSR02-7.docx', case: 'CASE-2026-0041', t: '昨天' },
              { f: 'F1-照片附件.pdf', case: 'CASE-2026-0040', t: '3 天前' },
            ].map((u, i) => (
              <div key={i} className="row gap-8" style={{
                padding: '8px 0',
                borderTop: i ? '1px solid var(--line)' : 'none',
              }}>
                <Icon name={u.f.endsWith('.pdf') ? 'pdf' : u.f.endsWith('.docx') ? 'file' : 'image'}
                      size={12} style={{ color: 'var(--ink-3)' }} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="text-xs text-mono" style={{
                    whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                  }}>{u.f}</div>
                  <div className="text-xs text-muted">{u.case}</div>
                </div>
                <div className="text-xs text-muted">{u.t}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, {
  ChecklistScreen, NonconformityScreen, PlotRegistryScreen, TemplateScreen, DriveScreen,
});
