// ── LAUNCH / PROJECT GATE ────────────────────────────────────────────────────
// Launch rules:
// - AccessTier says who is using the system.
// - ActiveProject says where work happens.
// - No signed-in user: Settings/account setup only.
// - Limited/Unlimited signed-in user + no projects: project-create splash.
// - Limited/Unlimited signed-in user + projects: project-select splash every launch.
// - Backstage access auto-enters the System scope initialized by startup authority.

window.LaunchState = {
  auth: null,
  settings: null,
  projects: [],
  activeProject: '',
  activeProjectSerial: '',
  backstage: false,
  enteredWorkspace: false
};

const LaunchState = window.LaunchState;

function isBackstageAuth(auth) {
  const tier = String(auth?.tier || auth?.accessTier || '').trim().toLowerCase();
  return tier === 'backstage';
}

function isRealProject(project) {
  if (!project) return false;
  const name = String(project.name || '').trim().toLowerCase();
  return Boolean(project.serialNo || project.location || project.path) && !['system', 'backstage', 'universal'].includes(name);
}

function launchSetHidden(id, hidden) {
  const el = byId(id);
  if (el) el.hidden = Boolean(hidden);
}

function launchShowOnly(panelId) {
  ['launch-account-required', 'launch-project-required', 'launch-project-select'].forEach(id => {
    launchSetHidden(id, id !== panelId);
  });
}

function setLaunchVisible(visible) {
  const gate = byId('launch-gate');
  if (!gate) return;
  gate.hidden = !visible;
  document.body.classList.toggle('launch-active', Boolean(visible));
}

function setLaunchSubtitle(text) {
  const el = byId('launch-subtitle');
  if (el) el.textContent = text || '';
}

function setBootSplashVisible(visible, text = 'Loading workspace') {
  const splash = byId('project-switch-splash');
  const label = byId('project-splash-text');
  if (label && text) label.textContent = text;
  if (!splash) return;
  splash.classList.toggle('active', Boolean(visible));
  splash.setAttribute('aria-hidden', visible ? 'false' : 'true');
}

function projectCardSummary(project) {
  return String(project.summary || project.description || project.notes || 'no recent activity')
    .trim()
    .slice(0, 120);
}

function projectCardMeta(project) {
  const location = String(project.location || project.path || '').trim();
  if (project.updatedAt) return `Updated ${new Date(project.updatedAt).toLocaleDateString()}`;
  if (location) return location;
  return project.serialNo ? `serial ${project.serialNo}` : 'project';
}

function renderLaunchProjectCards(projects) {
  const grid = byId('launch-project-grid');
  if (!grid) return;

  const realProjects = (projects || []).filter(isRealProject);
  grid.innerHTML = realProjects.map((project, index) => {
    const name = esc(project.name || 'Untitled Project');
    const summary = esc(projectCardSummary(project));
    const meta = esc(projectCardMeta(project));
    const serial = esc(project.serialNo || '');
    const color = String((index % 4) + 1);

    return `
      <button class="launch-project-card" type="button" data-launch-project="${serial || esc(project.name || '')}" data-color="${color}">
        <div class="launch-project-card-title">${name}</div>
        <div class="launch-project-card-summary">${summary}</div>
        <div class="launch-project-card-meta">${meta}</div>
      </button>
    `;
  }).join('');

  grid.querySelectorAll('[data-launch-project]').forEach(btn => {
    btn.addEventListener('click', () => {
      const key = btn.getAttribute('data-launch-project') || '';
      void launchSelectProject(key);
    });
  });
}

async function fetchLaunchStatus() {
  const status = await api('/status');
  if (!status?.ok) return status;
  const controller = status.controller?.state || status.controller || {};
  const serial = String(status.activeProjectSerial || status.scopeSerial || controller.projectSerial || '').trim();
  const name = String(status.activeProject || status.project || controller.activeProject || controller.projectName || '').trim();
  const mode = String(status.startupMode || status.projectMode || controller.projectMode || '').trim().toLowerCase();
  if (serial && !LaunchState.activeProjectSerial) LaunchState.activeProjectSerial = serial;
  if (name && !LaunchState.activeProject) LaunchState.activeProject = name;
  if (LaunchState.backstage && (serial === '00' || mode === 'system')) {
    LaunchState.activeProjectSerial = '00';
    LaunchState.activeProject = 'System';
  }
  return status;
}

async function fetchLaunchProjects() {
  const data = await api('/projects');
  if (!data?.ok) return [];
  LaunchState.activeProject = String(data.activeProject || data.project?.name || '').trim();
  LaunchState.activeProjectSerial = String(data.projectSerial || data.activeProjectSerial || data.project?.serialNo || data.serialNo || '').trim();
  const projects = Array.isArray(data.projects) ? data.projects : [];
  return projects.filter(isRealProject);
}

async function launchSelectProject(projectKey) {
  const key = String(projectKey || '').trim();
  if (!key) return;

  const data = window.DeckProject?.initiateProjectSwitch
    ? await window.DeckProject.initiateProjectSwitch({ serialNo: key, name: key, source: 'launch' })
    : await api('/projects/select', 'POST', { serialNo: key, name: key, source: 'launch' });

  if (!data?.ok) {
    toast(data?.message || data?.error || 'Project select failed');
    appendLog(`✗ project select failed: ${data?.message || data?.error || 'unknown'}`, 'fail');
    return;
  }

  LaunchState.enteredWorkspace = true;
  appendLog(`✓ project selected: ${data.project?.name || data.activeProject || key}`, 'pass');
  if (!window.DeckProject?.initiateProjectSwitch && window.MonitorProject?.renderProject) await window.MonitorProject.renderProject(data.projectState || data);
  setLaunchVisible(false);
  activateTab('project');
}

async function launchCreateProject(nameInputId, errorId) {
  const input = byId(nameInputId);
  const error = byId(errorId);
  const name = String(input?.value || '').trim();

  if (error) error.textContent = '';
  if (!name) {
    if (error) error.textContent = 'Enter a project name.';
    return;
  }

  const data = await api('/projects/create', 'POST', { name });
  if (!data?.ok) {
    const msg = data?.message || data?.error || 'Project creation failed';
    if (error) error.textContent = msg;
    toast(msg);
    return;
  }

  const projects = await fetchLaunchProjects();
  LaunchState.projects = projects;

  const created = projects.find(p => String(p.name || '').trim().toLowerCase() === name.toLowerCase()) || projects[projects.length - 1];
  if (created) {
    await launchSelectProject(created.serialNo || created.name);
    return;
  }

  await renderLaunchState();
}

async function enterActiveLaunchProject() {
  LaunchState.enteredWorkspace = true;
  setLaunchVisible(false);
  if (window.MonitorProject?.renderProject) {
    const data = await api('/project/header-meta');
    if (data?.ok) window.MonitorProject.renderProject(data);
  }
  setBootSplashVisible(false);
  activateTab('project');
}

function showLaunchAccountRequired() {
  setLaunchSubtitle('Account setup required');
  launchShowOnly('launch-account-required');
  setLaunchVisible(true);
  activateTab('settings');
}

function showLaunchCreateProject() {
  setLaunchSubtitle('Create a project to begin');
  launchShowOnly('launch-project-required');
  setLaunchVisible(true);
}

function showLaunchProjectSelect(projects) {
  setLaunchSubtitle('Select project');
  launchShowOnly('launch-project-select');
  renderLaunchProjectCards(projects);
  launchSetHidden('launch-backstage-row', true);
  setLaunchVisible(true);
}

function hasLaunchActiveProject() {
  const name = String(LaunchState.activeProject || '').trim().toLowerCase();
  const serial = String(LaunchState.activeProjectSerial || '').trim();
  if (LaunchState.backstage && (serial === '00' || name === 'system')) return true;
  return Boolean(name && !['system', 'backstage', 'universal'].includes(name));
}

async function renderLaunchState() {
  const auth = LaunchState.auth || {};
  const signedIn = isSignedInAuth(auth);
  const projects = LaunchState.projects.filter(isRealProject);

  if (!signedIn) {
    showLaunchAccountRequired();
    return;
  }

  if (hasLaunchActiveProject()) {
    await enterActiveLaunchProject();
    return;
  }

  if (LaunchState.backstage) {
    await enterActiveLaunchProject();
    return;
  }

  if (!projects.length) {
    showLaunchCreateProject();
    return;
  }

  showLaunchProjectSelect(projects);
}

async function bootLaunchGate() {
  setBootSplashVisible(true, 'Loading workspace');
  try {
    LaunchState.settings = await SettingsStore.load();
    LaunchState.auth = await refreshAccountUI();
    LaunchState.backstage = isBackstageAuth(LaunchState.auth);
    await fetchLaunchStatus();
    LaunchState.projects = await fetchLaunchProjects();
    await fetchLaunchStatus();

    await enforceAgreementGate(LaunchState.settings || {}, LaunchState.auth || {});
    if (agreementGateActive) {
      setBootSplashVisible(false);
      showLaunchAccountRequired();
      return;
    }

    await renderLaunchState();
  } finally {
    if (!LaunchState.enteredWorkspace) setBootSplashVisible(false);
  }
}

function wireLaunchGateControls() {
  on('launch-settings-btn', 'click', () => {
    setLaunchVisible(false);
    activateTab('settings');
  });

  on('launch-account-settings-btn', 'click', () => {
    setLaunchVisible(false);
    activateTab('settings');
  });

  on('launch-recovery-btn', 'click', () => {
    window.location.href = '/recovery';
  });

  on('launch-create-project-btn', 'click', () => {
    void launchCreateProject('launch-project-name', 'launch-create-error');
  });

  on('launch-project-name', 'keydown', event => {
    if (event.key === 'Enter') {
      event.preventDefault();
      void launchCreateProject('launch-project-name', 'launch-create-error');
    }
  });

  on('launch-create-open-btn', 'click', () => {
    launchSetHidden('launch-create-inline', false);
    byId('launch-project-name-inline')?.focus();
  });

  on('launch-create-cancel-btn', 'click', () => {
    launchSetHidden('launch-create-inline', true);
  });

  on('launch-create-project-inline-btn', 'click', () => {
    void launchCreateProject('launch-project-name-inline', 'launch-create-inline-error');
  });

  on('launch-project-name-inline', 'keydown', event => {
    if (event.key === 'Enter') {
      event.preventDefault();
      void launchCreateProject('launch-project-name-inline', 'launch-create-inline-error');
    }
  });
}
