// F1 — Desktop 3-pane layout

const F1Desktop = ({ caseData, sections, completion, onPreviewPdf }) => {
  const visibleSections = completion === 'empty' ? [] :
                          completion === 'half' ? sections.slice(0, 2) :
                          sections;
  const [activeId, setActiveId] = React.useState(visibleSections[0]?.id || null);
  React.useEffect(() => {
    if (!visibleSections.find((s) => s.id === activeId)) {
      setActiveId(visibleSections[0]?.id || null);
    }
  }, [completion]);

  const active = visibleSections.find((s) => s.id === activeId);

  return (
    <div className="app-shell">
      {/* Left: section list */}
      <div style={{ width: 280, flexShrink: 0, borderRight: '1px solid var(--line)',
                    background: 'var(--surface)', display: 'flex', flexDirection: 'column' }}>
        <div style={{ padding: '14px 16px', borderBottom: '1px solid var(--line)' }}>
          <div className="row" style={{ justifyContent: 'space-between' }}>
            <div className="text-sm font-semibold">地號區塊 · {visibleSections.length}</div>
            <button className="btn btn-sm btn-primary"><Icon name="plus" size={12} />新增</button>
          </div>
          <div className="text-xs text-muted mt-4">點擊查看 / 上傳照片</div>
        </div>
        <div style={{ flex: 1, overflowY: 'auto', padding: 8 }}>
          {visibleSections.length === 0 ? (
            <div style={{ padding: '40px 16px', textAlign: 'center', color: 'var(--ink-3)' }}>
              <Icon name="image" size={32} style={{ opacity: .4, marginBottom: 12 }} />
              <div className="text-sm">尚無區塊</div>
              <button className="btn btn-sm btn-primary mt-12"><Icon name="plus" size={12} />新增第一個區塊</button>
            </div>
          ) : visibleSections.map((s) => (
            <button key={s.id} onClick={() => setActiveId(s.id)}
                    className="card-flat"
                    style={{
                      display: 'flex', gap: 10, padding: 8, marginBottom: 6,
                      width: '100%', cursor: 'pointer', textAlign: 'left',
                      border: activeId === s.id ?
                              '1.5px solid var(--accent)' :
                              '1px solid var(--line)',
                      background: activeId === s.id ?
                                  'color-mix(in srgb, var(--accent) 6%, var(--surface))' :
                                  'var(--surface)',
                    }}>
              <div style={{ width: 60, height: 60, borderRadius: 6, overflow: 'hidden', flexShrink: 0 }}>
                <SatelliteSVG seed={s.orderIndex * 7} label="" area="" />
              </div>
              <div style={{ minWidth: 0, flex: 1 }}>
                <div className="row" style={{ justifyContent: 'space-between' }}>
                  <div className="text-xs text-mono text-muted">#{String(s.orderIndex).padStart(2, '0')}</div>
                  <div className="text-xs text-mono text-muted">{s.photos.length} 張</div>
                </div>
                <div className="text-sm font-medium" style={{ marginTop: 2 }}>
                  {s.sectionName} {s.parcelNo}
                </div>
                <div className="text-xs text-muted" style={{
                  whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'
                }}>
                  {s.township} · {s.areaHa.toFixed(3)} ha
                </div>
              </div>
            </button>
          ))}
        </div>
        <div style={{ padding: 12, borderTop: '1px solid var(--line)' }}>
          <div className="row gap-6 text-xs text-muted" style={{ marginBottom: 8 }}>
            <Icon name="cloud_check" size={12} style={{ color: 'var(--ok)' }} />
            <span>Drive 已同步</span>
            <span style={{ flex: 1 }} />
            <span className="text-mono">剛剛</span>
          </div>
          <button className="btn btn-primary" style={{ width: '100%' }} onClick={onPreviewPdf}>
            <Icon name="pdf" size={14} />匯出附件 PDF
          </button>
        </div>
      </div>

      {/* Middle: section detail with photo grid */}
      <div style={{ flex: 1, overflowY: 'auto', padding: 24, minWidth: 0 }}>
        {!active ? (
          <div style={{ height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center',
                        flexDirection: 'column', color: 'var(--ink-3)', textAlign: 'center' }}>
            <Icon name="image" size={48} style={{ opacity: .35 }} />
            <div className="text-md mt-12">選擇左側區塊以開始</div>
            <div className="text-sm text-muted mt-4">或點「新增」上傳新的衛星地號圖</div>
          </div>
        ) : (
          <div className="fade-in">
            <div className="row" style={{ justifyContent: 'space-between', marginBottom: 16 }}>
              <div>
                <div className="text-xs text-mono text-muted">區塊 #{String(active.orderIndex).padStart(2, '0')}</div>
                <div className="text-2xl font-semibold mt-4">{active.sectionName} {active.parcelNo}</div>
                <div className="text-sm text-muted mt-4">
                  {active.township} · {active.farmerName} · {active.areaHa.toFixed(4)} ha
                </div>
              </div>
              <div className="row gap-8">
                <button className="btn"><Icon name="edit" size={13} />編輯</button>
                <button className="btn btn-danger"><Icon name="trash" size={13} />刪除</button>
              </div>
            </div>

            <div className="row gap-16" style={{ alignItems: 'flex-start' }}>
              <div className="card" style={{ width: 360, padding: 0, overflow: 'hidden', flexShrink: 0 }}>
                <div style={{ height: 240 }}>
                  <SatelliteSVG seed={active.orderIndex * 7}
                                label={`${active.sectionName} ${active.parcelNo}`}
                                area={`${active.areaHa.toFixed(4)} ha`} />
                </div>
                <div style={{ padding: 14 }}>
                  <div className="text-sm font-semibold mb-8">地號 metadata</div>
                  <div className="kv"><span className="k">縣市鄉鎮</span><span className="v">{active.township}</span></div>
                  <div className="kv"><span className="k">地段名</span><span className="v">{active.sectionName}</span></div>
                  <div className="kv"><span className="k">地號</span><span className="v text-mono">{active.parcelNo}</span></div>
                  <div className="kv"><span className="k">農戶</span><span className="v">{active.farmerName}</span></div>
                  <div className="kv"><span className="k">所有權人</span><span className="v">{active.ownerName}</span></div>
                  <div className="kv"><span className="k">申請面積</span><span className="v text-mono">{active.areaHa.toFixed(4)} ha</span></div>
                  <div className="kv"><span className="k">驗證面積</span><span className="v text-mono">{active.verifiedAreaHa.toFixed(4)} ha</span></div>
                </div>
              </div>

              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="row" style={{ justifyContent: 'space-between', marginBottom: 12 }}>
                  <div className="text-md font-semibold">現場照片 · {active.photos.length} 張</div>
                  <div className="row gap-6">
                    <button className="btn btn-sm"><Icon name="upload" size={12} />上傳</button>
                    <button className="btn btn-sm"><Icon name="camera" size={12} />掃描</button>
                  </div>
                </div>

                <div className="card mb-12" style={{ padding: 12 }}>
                  <label className="label">本區塊稽核工作說明 (將寫入 PDF caption 補充)</label>
                  <textarea className="textarea" rows={2}
                            placeholder={`例:檢視${active.sectionName}田間管理、確認緩衝帶設置、抽查農藥使用紀錄...`}
                            defaultValue={active.workNote || ''} />
                </div>
                <div className="photo-grid cols-3">
                  {active.photos.map((p, i) => (
                    <div key={p.id} className="photo-with-note">
                      <div className="photo-tile" style={{ cursor: 'pointer' }}>
                        <PhotoSVG seed={p.id.charCodeAt(1) + i * 3}
                                  kind={['field', 'crop', 'facility', 'machine', 'water'][i % 5]} />
                        <div className="ph-num">{String(i + 1).padStart(2, '0')}</div>
                        {!p.uploaded && (
                          <div className="ph-progress">
                            <Icon name="cloud_up" size={20} />
                            <div className="progress-bar"><div className="progress-bar-fill" style={{ width: `${p.progress || 0}%` }} /></div>
                            <div className="text-mono">{Math.floor(p.progress || 0)}%</div>
                          </div>
                        )}
                        {p.uploaded && (
                          <div style={{ position: 'absolute', top: 6, right: 6,
                                        width: 20, height: 20, borderRadius: 10,
                                        background: 'rgba(0,0,0,.55)', color: 'white',
                                        display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                            <Icon name="check" size={12} />
                          </div>
                        )}
                      </div>
                      <input className="input" placeholder="這張在做什麼?(例:抽查農藥儲存)"
                             defaultValue={p.note || ''}
                             style={{ marginTop: 6, fontSize: 11.5, padding: '5px 8px' }} />
                    </div>
                  ))}
                  <div className="photo-tile" style={{
                    border: '1.5px dashed var(--line-2)',
                    background: 'var(--surface)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    flexDirection: 'column', gap: 4, color: 'var(--ink-3)',
                  }}>
                    <Icon name="plus" size={22} />
                    <span className="text-xs">拖入或點擊</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Right: live PDF preview */}
      <div style={{ width: 360, flexShrink: 0, borderLeft: '1px solid var(--line)',
                    background: 'var(--surface-2)', display: 'flex', flexDirection: 'column' }}>
        <div style={{ padding: '14px 16px', borderBottom: '1px solid var(--line)',
                      background: 'var(--surface)' }}>
          <div className="row" style={{ justifyContent: 'space-between' }}>
            <div className="text-sm font-semibold">PDF 即時預覽</div>
            <button className="btn btn-sm btn-ghost"><Icon name="eye" size={12} /></button>
          </div>
          <div className="text-xs text-muted mt-4">附件(2) 現場稽核照片紀錄</div>
        </div>
        <div style={{ flex: 1, overflowY: 'auto', padding: 16 }}>
          <PdfA4Page caseData={caseData} sections={visibleSections} layout={2} pageNum={1} />
          {visibleSections.length > 0 && (
            <>
              <div style={{ height: 12 }} />
              <PdfA4Page caseData={caseData} sections={visibleSections} layout={2} pageNum={2} isContinuation />
            </>
          )}
        </div>
        <div style={{ padding: 12, borderTop: '1px solid var(--line)', background: 'var(--surface)' }}>
          <button className="btn btn-primary" style={{ width: '100%' }} onClick={onPreviewPdf}>
            <Icon name="download" size={14} />下載 PDF · {visibleSections.length * 2} 頁
          </button>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { F1Desktop });
