// Bootstrap: auth gate (server backend only), workspace selection, and the
// initial mount. Runs after all other scripts have loaded.

function LoginScreen({ onSuccess }) {
  const [password, setPassword] = React.useState('');
  const [error, setError] = React.useState('');
  const [loading, setLoading] = React.useState(false);

  async function submit(e) {
    e.preventDefault();
    if (!password || loading) return;
    setLoading(true); setError('');
    const ok = await window.serverAPI.login(password);
    if (ok) { onSuccess(); return; }
    setLoading(false);
    setError('Wrong password');
  }

  return (
    <div className="boot-screen">
      <form className="boot-card" onSubmit={submit}>
        <div className="boot-title">Cookie Planner</div>
        <div className="boot-sub">Enter the shared password to continue.</div>
        <input
          type="password" autoFocus placeholder="Password"
          value={password} onChange={e => setPassword(e.target.value)}
          className="boot-input"
        />
        {error && <div className="boot-error">{error}</div>}
        <button className="btn btn-primary boot-btn" disabled={loading} type="submit">
          {loading ? 'Checking…' : 'Enter'}
        </button>
      </form>
    </div>
  );
}

function LoadingScreen() {
  return <div className="boot-screen"><div className="boot-loading">Loading…</div></div>;
}

// This app is used by one small team sharing one shared password — there's
// no need for a workspace picker or "create your first workspace" screen.
// Everyone always lands in the same single workspace, auto-created the
// first time anyone logs in.
const SHARED_WORKSPACE_NAME = 'Main';

async function boot() {
  const root = window.__tonyplannerRoot || (window.__tonyplannerRoot = ReactDOM.createRoot(document.getElementById('root')));
  root.render(<LoadingScreen />);

  if (window.serverAPI) {
    let authed = false;
    try { authed = await window.serverAPI.checkSession(); } catch (e) {}
    if (!authed) {
      root.render(<LoginScreen onSuccess={boot} />);
      return;
    }

    let list = [];
    try { list = await window.serverAPI.listWorkspaces(); } catch (e) {}
    // Prefer the shared name if it exists; otherwise fall back to whatever's
    // already there (covers workspaces created before this change) rather
    // than silently starting a second, empty one.
    let name = list.find(w => w.name === SHARED_WORKSPACE_NAME)?.name || (list[0] && list[0].name) || null;
    if (!name) {
      try {
        await window.serverAPI.createWorkspace(SHARED_WORKSPACE_NAME, window.seedData());
        name = SHARED_WORKSPACE_NAME;
      } catch (e) {
        console.warn('TonyPlanner: could not auto-create shared workspace —', e);
        root.render(<LoadingScreen />);
        return;
      }
    }
    window.serverAPI.setActiveWorkspace(name);
    await window.initServerWorkspace(name);
  } else {
    window.initLocalOrElectron();
  }

  root.render(<App />);
}

window.appBoot = boot;
boot();
