// ─── Create instance screen ───
function CreateScreen({ setScreen, toast, instance, setInstance }) {
  const [loading, setLoading] = React.useState(false);
  async function go() {
    setLoading(true);
    try {
      const data = await apiRequest('/api/instance', { method: 'POST' });
      setInstance(data);
      toast('云端电脑创建中...');
      setScreen('booting');
    } catch (ex) {
      if (ex.code === 'err_instance_exists') {
        try {
          const data = await apiRequest('/api/instance');
          setInstance(data);
          setScreen(data.availability === 'ready' ? 'dashboard' : 'booting');
        } catch { /* ignore */ }
      } else {
        toast(errText(ex.code || ex.message), 'error');
      }
    } finally {
      setLoading(false);
    }
  }
  return (
    <div className="stage stage--center">
      <div className="win" style={{ maxWidth: 540, width: '100%' }}>
        <div className="win__bar">
          <div className="dots"><i/><i/><i/></div>
          <div className="title">provision.sh</div>
          <div className="meta">READY</div>
        </div>
        <div className="win__body" style={{ padding: 40, textAlign: 'center' }}>
          <div style={{ animation: 'shrimp-bob 2.8s ease-in-out infinite', display: 'inline-block' }}>
            <Shrimp size={140} mood="excited"/>
          </div>
          <h2 style={{ fontSize: 20, marginTop: 16, marginBottom: 8 }}>
            创建你的 OpenClaw 云端电脑
          </h2>
          <p className="small muted mono" style={{ marginBottom: 22 }}>
            {'>'} 点击按钮，我们将启动一个专属容器<br/>
            {'>'} 预计耗时 1~2 分钟
          </p>

          <div className="row" style={{ justifyContent: 'center', gap: 8, marginBottom: 22 }}>
            <span className="chip">独立容器</span>
            <span className="chip chip--shrimp">专属工作空间</span>
          </div>

          <button className="btn btn--primary btn--lg" onClick={go} disabled={loading}>
            {loading ? '启动中...' : '▸ 立即创建'}
          </button>

          <div className="tiny muted mono mt-4">
            {'// 使用邀请制 · 无需信用卡'}
          </div>
        </div>
      </div>
    </div>
  );
}
window.CreateScreen = CreateScreen;

// ─── Booting screen ─── Poll /api/instance until availability === 'ready'
function BootingScreen({ setScreen, instance, setInstance, toast }) {
  // Progress is approximate — derived from elapsed time (real provisioning takes 1-2 min).
  const [progress, setProgress] = React.useState(12);
  const [step, setStep] = React.useState(1);
  const [logs, setLogs] = React.useState([
    { t: '00:00', msg: 'requesting container image', ok: true },
  ]);

  React.useEffect(() => {
    let pollToken = 0;
    let progressIv = null;
    const myToken = ++pollToken;

    // Fake progress bar (real boot status is binary: loading vs ready)
    progressIv = setInterval(() => {
      setProgress(p => Math.min(95, p + 2 + Math.random() * 3));
    }, 700);

    async function poll() {
      if (myToken !== pollToken) return;
      try {
        const data = await apiRequest('/api/instance');
        if (myToken !== pollToken) return;
        setInstance(data);
        // Step progression based on status
        if (data.status === 'running' && step < 2) setStep(2);
        if (data.health_status === 'healthy' && step < 3) setStep(3);
        // Add log lines
        setLogs(l => {
          const last = l[l.length - 1];
          const msg = `status=${data.status}${data.health_status ? ' health=' + data.health_status : ''}`;
          if (last && last.msg === msg) return l;
          const t = String(l.length * 3).padStart(2, '0');
          return [...l, { t: `00:${t}`, msg, ok: data.status !== 'error' }];
        });
        if (data.availability === 'ready') {
          setProgress(100);
          clearInterval(progressIv);
          toast('云端电脑已就绪');
          setTimeout(() => setScreen('dashboard'), 400);
          return;
        }
        if (data.status === 'error') {
          clearInterval(progressIv);
          toast('启动失败', 'error');
          return;
        }
      } catch (ex) {
        if (ex.code === 'err_instance_not_found') {
          clearInterval(progressIv);
          setScreen('create');
          return;
        }
      }
      setTimeout(poll, 2400);
    }
    setTimeout(poll, 800);

    return () => {
      pollToken++;
      clearInterval(progressIv);
    };
  }, []); // eslint-disable-line

  const availability = instance?.availability || 'loading';

  return (
    <div className="stage stage--center">
      <div className="win" style={{ maxWidth: 620, width: '100%' }}>
        <div className="win__bar">
          <div className="dots"><i/><i/><i/></div>
          <div className="title">bootstrap.log</div>
          <div className="meta">BOOTING · {Math.floor(progress)}%</div>
        </div>
        <div className="win__body" style={{ padding: 28 }}>
          <div className="steps mb-4" style={{ justifyContent: 'space-between' }}>
            <div className="step done">
              <div className="step__node">✓</div>
              <div className="step__label">账号已登录</div>
            </div>
            <div className="step__line done"/>
            <div className={'step ' + (step >= 1 ? 'done' : '')}>
              <div className="step__node">✓</div>
              <div className="step__label">容器已创建</div>
            </div>
            <div className={'step__line ' + (step >= 2 ? 'done' : '')}/>
            <div className={'step ' + (step >= 2 ? (step >= 3 ? 'done' : 'active') : '')}>
              <div className="step__node">{step >= 3 ? '✓' : '·'}</div>
              <div className="step__label">系统初始化</div>
            </div>
            <div className={'step__line ' + (step >= 3 ? 'done' : '')}/>
            <div className={'step ' + (availability === 'ready' ? 'done' : 'active')}>
              <div className="step__node">{availability === 'ready' ? '✓' : '·'}</div>
              <div className="step__label">健康检查</div>
            </div>
          </div>

          <div style={{ position: 'relative', marginBottom: 8 }}>
            <div className="pbar pbar--amber" style={{ height: 24 }}>
              <div className="pbar__fill" style={{ width: `${progress}%` }}/>
            </div>
            <div style={{
              position: 'absolute',
              left: `calc(${progress}% - 22px)`,
              top: -8,
              animation: 'shrimp-wiggle 0.4s ease-in-out infinite',
              transition: 'left 0.7s ease',
            }}>
              <Shrimp size={36} mood="excited"/>
            </div>
          </div>
          <div className="between tiny mono muted mb-4">
            <span>STATUS: {instance?.status || 'provisioning'}</span>
            <span>{Math.floor(progress)}% · ETA {Math.max(5, 90 - Math.floor(progress * 0.9))}s</span>
          </div>

          <div className="term" style={{ minHeight: 160, fontSize: 12, padding: 12 }}>
            {logs.map((l, i) => (
              <div key={i}>
                <span className="comment">[{l.t}]</span> <span className="prompt">{l.ok ? '✓' : '✗'}</span> <span className={l.ok ? 'cmd' : 'err'}>{l.msg}</span>
              </div>
            ))}
            <div><span className="comment">[00:{logs.length*3}]</span> <span className="prompt">▸</span> <span className="cmd">{'waiting for ready...'}</span><span className="caret"/></div>
          </div>
        </div>
      </div>
    </div>
  );
}
window.BootingScreen = BootingScreen;
