// GS Car — Upload, Payment, Sign Contract screens

const ScreenUpload = ({ onClose, onPay }) => {
  const [step, setStep] = React.useState(1);
  const [photos, setPhotos] = React.useState(3);
  return (
    <div className="screen screen-enter">
      <StatusBar />
      <div className="nav-bar">
        <button className="icon-btn" onClick={onClose}><Icons.Close size={18} /></button>
        <div style={{ fontSize: 13, fontWeight: 600 }}>上架車盤</div>
        <div style={{ width: 36 }} />
      </div>
      <div style={{ padding: '0 20px 12px' }}>
        <div style={{ display: 'flex', gap: 6 }}>
          {[1, 2, 3].map(i => (
            <div key={i} style={{
              flex: 1, height: 3, borderRadius: 2,
              background: i <= step ? 'var(--accent)' : 'var(--bg-3)',
              transition: 'all 0.3s',
            }} />
          ))}
        </div>
        <div style={{ marginTop: 10, fontSize: 11, color: 'var(--ink-3)' }}>
          步驟 {step} / 3 · {step === 1 ? '基本資料' : step === 2 ? '相片上載' : '確認 + 付款'}
        </div>
      </div>

      <div className="scroll" style={{ padding: '8px 20px 100px' }}>
        {step === 1 && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <Field label="廠牌 / 型號" value="BMW M3 Competition" />
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <Field label="年份" value="2022" />
              <Field label="里數 (km)" value="18,500" />
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <Field label="變速箱" value="自動 8-Speed" />
              <Field label="燃料" value="Petrol" />
            </div>
            <Field label="售價 (HKD)" value="868,000" accent />
            <Field label="地區" value="中環" />
            <Field label="描述" value="一手車主、原廠保養紀錄齊全。M Performance 排氣..." multiline />
          </div>
        )}
        {step === 2 && (
          <div>
            <div className="label" style={{ marginBottom: 10 }}>相片（最多 10 張，已上載 {photos}）</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
              {Array.from({ length: 10 }).map((_, i) => (
                <div key={i} style={{
                  aspectRatio: '1',
                  background: i < photos ? `radial-gradient(ellipse at center, #2a2a35, #0a0a0e)` : 'var(--bg-2)',
                  border: i < photos ? '1px solid var(--line)' : '1px dashed var(--ink-4)',
                  borderRadius: 10,
                  display: 'grid', placeItems: 'center',
                  position: 'relative',
                }} onClick={() => i >= photos && setPhotos(p => Math.min(p + 1, 10))}>
                  {i < photos ? (
                    <div style={{ fontSize: 10, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)' }}>IMG_{i + 1}</div>
                  ) : (
                    <Icons.Plus size={20} />
                  )}
                  {i === 0 && i < photos && (
                    <div style={{
                      position: 'absolute', top: 4, left: 4,
                      background: 'var(--accent)', color: '#fff',
                      fontSize: 8, padding: '2px 5px', borderRadius: 3,
                      fontWeight: 700, letterSpacing: '0.05em',
                    }}>主圖</div>
                  )}
                </div>
              ))}
            </div>
            <div style={{
              marginTop: 16, padding: 12,
              background: 'var(--bg-2)', borderRadius: 10,
              fontSize: 11, color: 'var(--ink-2)', lineHeight: 1.5,
            }}>
              💡 建議影：外觀 4 角、內裝、儀錶板（顯示里數）、引擎室、車牌冊。增加買家信任度 +73%。
            </div>
          </div>
        )}
        {step === 3 && (
          <div>
            <div style={{
              padding: 16, background: 'var(--bg-1)', borderRadius: 14,
              border: '1px solid var(--line)',
            }}>
              <div className="meta">即將上架</div>
              <div style={{ fontSize: 16, fontWeight: 700, marginTop: 6 }}>2022 BMW M3 Competition</div>
              <div style={{ fontSize: 12, color: 'var(--ink-2)' }}>18,500 km · 中環 · 3 photos</div>
              <div style={{ marginTop: 10 }}><Price value={868000} size={20} accent /></div>
            </div>

            <div style={{ marginTop: 20 }}>
              <div className="meta" style={{ marginBottom: 10 }}>上架費</div>
              <div style={{
                padding: 16, background: 'linear-gradient(135deg, rgba(225,10,23,0.1), transparent)',
                borderRadius: 14, border: '1px solid rgba(225,10,23,0.3)',
              }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <div>
                    <div style={{ fontSize: 12, color: 'var(--ink-2)' }}>30 日有效期</div>
                    <div style={{ fontSize: 24, fontWeight: 800, marginTop: 2, letterSpacing: '-0.02em' }}>HK$100</div>
                  </div>
                  <div style={{ fontSize: 10, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)' }}>
                    LISTING.FEE
                  </div>
                </div>
                <div style={{ fontSize: 11, color: 'var(--ink-2)', marginTop: 8, lineHeight: 1.5 }}>
                  ✓ 出現喺市場主頁 · ✓ AI Agent 推薦 · ✓ 30 日無限聯絡
                </div>
              </div>
            </div>

            <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 8 }}>
              <PayMethod logo="PayMe" desc="HSBC 即時轉帳" selected />
              <PayMethod logo="Stripe" desc="信用卡 / Apple Pay" />
              <PayMethod logo="FPS" desc="轉數快" />
            </div>
          </div>
        )}
      </div>

      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0,
        padding: '14px 20px 32px',
        background: 'rgba(8,8,10,0.95)', backdropFilter: 'blur(20px)',
        borderTop: '0.5px solid var(--line)',
        display: 'flex', gap: 10,
      }}>
        {step > 1 && (
          <button className="btn-secondary" onClick={() => setStep(s => s - 1)} style={{ flex: 0, padding: '14px 20px' }}>上一步</button>
        )}
        <button className="btn-primary" onClick={() => step < 3 ? setStep(s => s + 1) : onPay()} style={{ flex: 1 }}>
          {step < 3 ? '繼續' : '確認支付 HK$100'}
        </button>
      </div>
    </div>
  );
};

const Field = ({ label, value, multiline, accent }) => (
  <div>
    <div className="label" style={{ marginBottom: 6 }}>{label}</div>
    <div style={{
      padding: multiline ? '12px 14px' : '14px',
      background: 'var(--bg-2)', borderRadius: 10,
      border: '1px solid var(--line)',
      fontSize: 14, color: accent ? 'var(--accent-bright)' : 'var(--ink-0)',
      fontWeight: accent ? 700 : 500,
      minHeight: multiline ? 64 : 'auto',
      lineHeight: 1.5,
    }}>{value}</div>
  </div>
);

const PayMethod = ({ logo, desc, selected }) => (
  <div style={{
    padding: 14, borderRadius: 12,
    background: selected ? 'var(--accent-soft)' : 'var(--bg-2)',
    border: `1px solid ${selected ? 'var(--accent)' : 'var(--line)'}`,
    display: 'flex', alignItems: 'center', gap: 12,
  }}>
    <div style={{
      width: 40, height: 40, borderRadius: 8,
      background: 'var(--bg-3)', display: 'grid', placeItems: 'center',
      fontSize: 9, fontWeight: 700, fontFamily: 'var(--font-mono)',
      color: 'var(--ink-1)', letterSpacing: '0.05em',
    }}>{logo}</div>
    <div style={{ flex: 1 }}>
      <div style={{ fontSize: 13, fontWeight: 600 }}>{logo}</div>
      <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{desc}</div>
    </div>
    <div style={{
      width: 20, height: 20, borderRadius: '50%',
      border: `2px solid ${selected ? 'var(--accent)' : 'var(--ink-4)'}`,
      display: 'grid', placeItems: 'center',
    }}>
      {selected && <div style={{ width: 10, height: 10, borderRadius: '50%', background: 'var(--accent)' }} />}
    </div>
  </div>
);

const ScreenPaymentSuccess = ({ onDone }) => {
  React.useEffect(() => {
    const t = setTimeout(onDone, 2400);
    return () => clearTimeout(t);
  }, []);
  return (
    <div className="screen screen-enter" style={{
      background: 'radial-gradient(ellipse at 50% 30%, rgba(45,187,110,0.15), var(--bg-0) 60%)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      <StatusBar />
      <div style={{ textAlign: 'center', padding: 40 }}>
        <div className="ring-pulse" style={{
          width: 80, height: 80, borderRadius: '50%',
          background: 'var(--green)', margin: '0 auto',
          display: 'grid', placeItems: 'center',
        }}>
          <Icons.Check size={36} />
        </div>
        <div style={{ fontSize: 24, fontWeight: 800, marginTop: 28, letterSpacing: '-0.02em' }}>付款成功</div>
        <div style={{ fontSize: 13, color: 'var(--ink-2)', marginTop: 8, lineHeight: 1.5 }}>
          車盤已上架 · 30 日有效<br />
          HK$100 已透過 PayMe 扣除
        </div>
        <div style={{
          marginTop: 24, padding: '8px 14px',
          background: 'var(--bg-2)', borderRadius: 8,
          display: 'inline-block',
          fontFamily: 'var(--font-mono)', fontSize: 10,
          color: 'var(--ink-3)', letterSpacing: '0.05em',
        }}>TXN · GS-2026-04-A8B2C9</div>
      </div>
    </div>
  );
};

const ScreenSignContract = ({ listing, onBack, onComplete }) => {
  const canvasRef = React.useRef(null);
  const [hasSignature, setHasSignature] = React.useState(false);
  const [drawing, setDrawing] = React.useState(false);
  const [stage, setStage] = React.useState('sign'); // sign | generating | done

  React.useEffect(() => {
    const c = canvasRef.current;
    if (!c) return;
    const ctx = c.getContext('2d');
    ctx.strokeStyle = '#fff';
    ctx.lineWidth = 2.5;
    ctx.lineCap = 'round';
    ctx.lineJoin = 'round';
    let drawing = false;
    const start = (e) => {
      drawing = true; setDrawing(true);
      const rect = c.getBoundingClientRect();
      const t = e.touches ? e.touches[0] : e;
      ctx.beginPath();
      ctx.moveTo(t.clientX - rect.left, t.clientY - rect.top);
      e.preventDefault();
    };
    const move = (e) => {
      if (!drawing) return;
      const rect = c.getBoundingClientRect();
      const t = e.touches ? e.touches[0] : e;
      ctx.lineTo(t.clientX - rect.left, t.clientY - rect.top);
      ctx.stroke();
      setHasSignature(true);
      e.preventDefault();
    };
    const end = () => { drawing = false; setDrawing(false); };
    c.addEventListener('mousedown', start);
    c.addEventListener('mousemove', move);
    window.addEventListener('mouseup', end);
    c.addEventListener('touchstart', start);
    c.addEventListener('touchmove', move);
    window.addEventListener('touchend', end);
    return () => {
      c.removeEventListener('mousedown', start);
      c.removeEventListener('mousemove', move);
      window.removeEventListener('mouseup', end);
      c.removeEventListener('touchstart', start);
      c.removeEventListener('touchmove', move);
      window.removeEventListener('touchend', end);
    };
  }, []);

  const clear = () => {
    const c = canvasRef.current;
    c.getContext('2d').clearRect(0, 0, c.width, c.height);
    setHasSignature(false);
  };

  const submit = () => {
    setStage('generating');
    setTimeout(() => setStage('done'), 1800);
  };

  return (
    <div className="screen screen-enter">
      <StatusBar />
      <div className="nav-bar">
        <button className="icon-btn" onClick={onBack}><Icons.Back size={18} /></button>
        <div style={{ fontSize: 13, fontWeight: 600 }}>電子簽署合約</div>
        <div style={{ width: 36 }} />
      </div>

      {stage === 'sign' && (
        <div className="scroll" style={{ padding: '0 20px 100px' }}>
          {/* Contract preview */}
          <div style={{
            background: '#f5f5f0', color: '#08080a',
            padding: '24px 22px', borderRadius: 12,
            fontFamily: 'Georgia, serif',
            boxShadow: '0 8px 24px rgba(0,0,0,0.4)',
          }}>
            <div style={{ textAlign: 'center', borderBottom: '1px solid #08080a', paddingBottom: 12, marginBottom: 14 }}>
              <div style={{ fontSize: 16, fontWeight: 700, letterSpacing: '0.04em' }}>二手車買賣合約</div>
              <div style={{ fontSize: 9, color: '#444', marginTop: 4, letterSpacing: '0.1em' }}>USED VEHICLE SALE AGREEMENT</div>
            </div>
            <div style={{ fontSize: 10, lineHeight: 1.7 }}>
              <div style={{ marginBottom: 8 }}><b>合約編號：</b>GS-CT-2026-0428-{listing.id.toUpperCase()}</div>
              <div style={{ marginBottom: 8 }}><b>日期：</b>2026 年 4 月 28 日</div>
              <div style={{ marginBottom: 12, paddingTop: 8, borderTop: '1px dashed #999' }}>
                <b>車輛：</b>{listing.year} {listing.make} {listing.model}<br />
                <b>里數：</b>{listing.mileage.toLocaleString()} km<br />
                <b>成交價：</b>HK${listing.price.toLocaleString()}
              </div>
              <div style={{ marginBottom: 12 }}>
                <b>賣方：</b>{listing.seller.name}<br />
                <b>買方：</b>Marcus Lam
              </div>
              <div style={{ fontSize: 9, color: '#555', lineHeight: 1.6, marginTop: 12, paddingTop: 8, borderTop: '1px dashed #999' }}>
                雙方同意按上述條款進行該車輛之買賣交易，並已就車輛現況達成共識。本合約以電子簽署方式訂立，根據香港《電子交易條例》第 553 章具法律效力。車主轉名 TD25 表格仍須親身遞交運輸署。
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginTop: 16, paddingTop: 12, borderTop: '1px solid #08080a' }}>
                <div>
                  <div style={{ fontSize: 8, color: '#888', textTransform: 'uppercase', letterSpacing: '0.1em' }}>賣方簽署</div>
                  <div style={{ height: 36, marginTop: 4, fontFamily: 'cursive', fontSize: 18, fontStyle: 'italic' }}>D. Wong</div>
                  <div style={{ fontSize: 8, color: '#888', borderTop: '1px solid #444', paddingTop: 2 }}>已簽 · 2026-04-28 14:22</div>
                </div>
                <div>
                  <div style={{ fontSize: 8, color: '#888', textTransform: 'uppercase', letterSpacing: '0.1em' }}>買方簽署</div>
                  <div style={{ height: 36, marginTop: 4, color: '#aaa', fontSize: 9, paddingTop: 12 }}>等待簽署...</div>
                  <div style={{ fontSize: 8, color: '#aaa', borderTop: '1px dashed #888', paddingTop: 2 }}>—</div>
                </div>
              </div>
            </div>
          </div>

          {/* Signature pad */}
          <div style={{ marginTop: 20 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
              <div className="meta">喺下面用手指簽名 · 你係買方</div>
              <button onClick={clear} style={{ fontSize: 11, color: 'var(--ink-2)' }}>清除</button>
            </div>
            <div style={{
              background: '#08080a', borderRadius: 12,
              border: `1px dashed ${hasSignature ? 'var(--accent)' : 'var(--ink-4)'}`,
              height: 160, position: 'relative',
              transition: 'border-color 0.2s',
            }}>
              <canvas ref={canvasRef} width={350} height={160}
                style={{ width: '100%', height: '100%', touchAction: 'none', cursor: 'crosshair' }} />
              {!hasSignature && !drawing && (
                <div style={{
                  position: 'absolute', inset: 0,
                  display: 'grid', placeItems: 'center',
                  pointerEvents: 'none',
                  color: 'var(--ink-4)', fontSize: 12,
                  fontFamily: 'var(--font-mono)', letterSpacing: '0.1em',
                }}>SIGN HERE / 喺度簽</div>
              )}
              <div style={{
                position: 'absolute', bottom: 8, left: 12,
                fontSize: 9, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)',
                letterSpacing: '0.1em',
              }}>X ─────────────────</div>
            </div>
          </div>
        </div>
      )}

      {stage === 'generating' && (
        <div style={{ flex: 1, display: 'grid', placeItems: 'center', padding: 40 }}>
          <div style={{ textAlign: 'center' }}>
            <div style={{
              width: 64, height: 64, margin: '0 auto',
              border: '3px solid var(--bg-3)',
              borderTopColor: 'var(--accent)',
              borderRadius: '50%',
              animation: 'spin 0.8s linear infinite',
            }} />
            <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
            <div style={{ fontSize: 16, fontWeight: 700, marginTop: 24 }}>合併雙方簽名</div>
            <div style={{ fontSize: 12, color: 'var(--ink-2)', marginTop: 6 }}>用 PDFKit 生成 PDF...</div>
          </div>
        </div>
      )}

      {stage === 'done' && (
        <div className="scroll" style={{ padding: '0 20px 100px', textAlign: 'center' }}>
          <div className="ring-pulse" style={{
            width: 64, height: 64, borderRadius: '50%',
            background: 'var(--green)', margin: '24px auto 0',
            display: 'grid', placeItems: 'center',
          }}><Icons.Check size={28} /></div>
          <div style={{ fontSize: 22, fontWeight: 800, marginTop: 20 }}>合約已生成</div>
          <div style={{ fontSize: 12, color: 'var(--ink-2)', marginTop: 6 }}>
            雙方簽名 PDF 已存入雲端
          </div>

          <div style={{
            marginTop: 24, padding: 16,
            background: 'var(--bg-1)', borderRadius: 14,
            border: '1px solid var(--line)',
            textAlign: 'left',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14, paddingBottom: 14, borderBottom: '0.5px solid var(--line)' }}>
              <div style={{ width: 44, height: 44, borderRadius: 8, background: 'rgba(225,10,23,0.12)', display: 'grid', placeItems: 'center', color: 'var(--accent)' }}>
                <Icons.Doc size={22} />
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 600 }}>GS-CT-2026-0428-{listing.id.toUpperCase()}.pdf</div>
                <div style={{ fontSize: 10, color: 'var(--ink-3)' }}>248 KB · A4 · 1 頁</div>
              </div>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
              <button className="btn-secondary" style={{ fontSize: 12, padding: '12px' }}><Icons.Share size={14} /> 分享</button>
              <button className="btn-secondary" style={{ fontSize: 12, padding: '12px' }}><Icons.Doc size={14} /> 下載</button>
            </div>
          </div>
          <div style={{
            marginTop: 16, padding: 12,
            background: 'var(--gold-soft)',
            borderRadius: 10, fontSize: 11, color: 'var(--gold)',
            lineHeight: 1.5, textAlign: 'left',
          }}>
            ⚠ 提示：請於成交後 72 小時內到運輸署遞交 TD25 過戶表格。
          </div>
        </div>
      )}

      {stage === 'sign' && (
        <div style={{
          position: 'absolute', bottom: 0, left: 0, right: 0,
          padding: '14px 20px 32px',
          background: 'rgba(8,8,10,0.95)', backdropFilter: 'blur(20px)',
          borderTop: '0.5px solid var(--line)',
        }}>
          <button onClick={submit} disabled={!hasSignature}
            className="btn-primary" style={{ width: '100%', opacity: hasSignature ? 1 : 0.4 }}>
            {hasSignature ? '確認簽署 + 生成 PDF' : '請先簽名'}
          </button>
        </div>
      )}
      {stage === 'done' && (
        <div style={{
          position: 'absolute', bottom: 0, left: 0, right: 0,
          padding: '14px 20px 32px',
          background: 'rgba(8,8,10,0.95)', backdropFilter: 'blur(20px)',
        }}>
          <button onClick={onComplete} className="btn-primary" style={{ width: '100%' }}>完成</button>
        </div>
      )}
    </div>
  );
};

window.ScreenUpload = ScreenUpload;
window.ScreenPaymentSuccess = ScreenPaymentSuccess;
window.ScreenSignContract = ScreenSignContract;
