// Project switcher + create modal. Phase 1 only scopes Claude Code sessions
// by project; Vault and Tracker remain global. Render the switcher in the
// TopBar between the breadcrumb and the right-side toolbar.

function ProjectSwitcher({ identity }) {
  const [open, setOpen] = React.useState(false);
  const [createModalOpen, setCreateModalOpen] = React.useState(false);
  const [assignVpsModalProject, setAssignVpsModalProject] = React.useState(null);
  const [perms, setPerms] = React.useState(null); // null while loading
  const projects = window.PROJECTS || [];
  const current = window.getCurrentProject ? window.getCurrentProject() : null;

  // Load the user's effective workspace permissions once, so we know
  // whether to show the "Crear proyecto" / "Gestionar VPS" options. The
  // legacy `identity === 'founder'` gate excluded every multi-tenant user
  // — including the owner of their own workspace — which is why brand-new
  // signups couldn't find anywhere to connect a VPS.
  React.useEffect(() => {
    let mounted = true;
    window.api?.('GET', '/api/workspace/me/permissions')
      .then((r) => { if (mounted) setPerms(r); })
      .catch(() => { if (mounted) setPerms({ permissions: [], legacyBypass: false }); });
    return () => { mounted = false; };
  }, [identity]);

  const has = (p) => !perms ? false : (perms.legacyBypass || perms.permissions.includes(p));
  const canCreateProject = has('project.create');
  const canManageVps = has('vps.connect') || has('vps.manage') || has('project.create');

  const switchTo = (id) => {
    window.setCurrentProject(id);
    setOpen(false);
  };

  // Buttons rendered next to the project switcher. We make them stand-alone
  // (instead of hiding them inside the switcher's dropdown) so a brand-new
  // owner sees "Conectar VPS" / "Crear proyecto" right at the top, no
  // hunting through menus.
  const sideButtons = (
    <>
      {canManageVps && (
        <button className="btn-reset" onClick={() => window.openVpsManager?.()}
          title="Gestionar VPS"
          style={{
            display: 'flex', alignItems: 'center', gap: 6, padding: '4px 10px', height: 26,
            border: '1px solid var(--border)', borderRadius: 999,
            background: 'rgba(79,142,255,.10)', color: '#9DBDF5', fontSize: 11.5, fontWeight: 500,
          }}>
          <Icon name="server" size={12} />
          <span>VPS</span>
        </button>
      )}
      {canCreateProject && (
        <button className="btn-reset" onClick={() => setCreateModalOpen(true)}
          title="Crear proyecto"
          style={{
            display: 'flex', alignItems: 'center', gap: 6, padding: '4px 10px', height: 26,
            border: '1px solid var(--border)', borderRadius: 999,
            color: 'var(--text-1)', fontSize: 11.5, fontWeight: 500,
          }}>
          <Icon name="plus" size={12} />
          <span>Proyecto</span>
        </button>
      )}
    </>
  );

  // Empty-state: no projects yet but the user can create one. Show the
  // side buttons by themselves (no project switcher to anchor against).
  if (projects.length === 0) {
    if (canCreateProject || canManageVps) {
      return (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          {sideButtons}
          {createModalOpen && <CreateProjectModal onClose={() => setCreateModalOpen(false)} />}
        </div>
      );
    }
    return null;
  }

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      <div style={{ position: 'relative' }}>
        <button
          className="btn-reset"
          onClick={() => setOpen((o) => !o)}
          title="Cambiar proyecto"
          style={{
            display: 'flex', alignItems: 'center', gap: 6,
            padding: '4px 10px', height: 26,
            border: '1px solid var(--border)', borderRadius: 999,
            background: open ? 'var(--bg-2)' : 'rgba(79,142,255,.06)',
            color: '#9DBDF5',
            fontSize: 11.5, fontWeight: 500,
          }}>
          <Icon name="folder-tree" size={12} />
          <span style={{ maxWidth: 140, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {current ? current.name : 'Sin proyecto'}
          </span>
          <Icon name="chevron-down" size={11} color="var(--text-2)" />
        </button>
        {open && (
          <>
            <div onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 40 }} />
            <div style={{
              position: 'absolute', top: '100%', left: 0, marginTop: 6,
              width: 280, padding: 4,
              background: 'var(--bg-1)', border: '1px solid var(--border)',
              borderRadius: 'var(--r-md)', boxShadow: '0 12px 32px rgba(0,0,0,.5)',
              zIndex: 50,
            }}>
              <div style={{ padding: '8px 10px 6px', fontSize: 10.5, color: 'var(--text-3)', letterSpacing: 0.6, textTransform: 'uppercase' }}>Proyecto activo</div>
              {projects.map((p) => {
                const active = current && p.id === current.id;
                return (
                  <button key={p.id} className="btn-reset" onClick={() => switchTo(p.id)}
                    style={{
                      display: 'flex', alignItems: 'center', gap: 10, width: '100%', padding: '8px 10px',
                      borderRadius: 6, textAlign: 'left',
                      background: active ? 'var(--bg-2)' : 'transparent',
                    }}
                    onMouseEnter={(e) => { if (!active) e.currentTarget.style.background = 'var(--bg-2)'; }}
                    onMouseLeave={(e) => { if (!active) e.currentTarget.style.background = 'transparent'; }}>
                    <span style={{ width: 20, height: 20, borderRadius: 5, background: 'rgba(79,142,255,.15)', color: '#9DBDF5', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                      <Icon name="folder" size={11} />
                    </span>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 12.5, fontWeight: 500, color: 'var(--text-0)', display: 'flex', alignItems: 'center', gap: 6, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                        <span style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.name}</span>
                        {p.vpsId ? (
                          <span title={`Corre en ${p.vpsId}`} style={{
                            fontSize: 9.5, padding: '1px 6px', borderRadius: 4,
                            background: 'rgba(168,85,247,.15)', color: '#C084FC',
                            letterSpacing: 0.4, textTransform: 'uppercase',
                          }}>{p.vpsId}</span>
                        ) : (
                          <span title="Este proyecto todavía no tiene un VPS asignado. Asígnale uno para correr Claude Code." style={{
                            fontSize: 9.5, padding: '1px 6px', borderRadius: 4,
                            background: 'rgba(245,158,11,.15)', color: '#F59E0B',
                            letterSpacing: 0.4, textTransform: 'uppercase',
                          }}>Sin VPS</span>
                        )}
                      </div>
                      <div className="mono" style={{ fontSize: 10.5, color: 'var(--text-2)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.rootDir}</div>
                    </div>
                    {active && <Icon name="check" size={13} color="var(--accent)" />}
                  </button>
                );
              })}
              {(canCreateProject || canManageVps) && (
                <>
                  <div style={{ height: 1, background: 'var(--border)', margin: '4px 0' }} />
                  {canManageVps && current && !current.vpsId && (
                    <button className="btn-reset"
                      onClick={() => { setOpen(false); setAssignVpsModalProject(current); }}
                      style={{
                        display: 'flex', alignItems: 'center', gap: 8, width: '100%', padding: '8px 10px',
                        borderRadius: 6, color: 'var(--accent)',
                      }}
                      onMouseEnter={(e) => e.currentTarget.style.background = 'var(--bg-2)'}
                      onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
                      <Icon name="link" size={13} />
                      <span style={{ fontSize: 12.5 }}>Asignar VPS a "{current.name}"…</span>
                    </button>
                  )}
                  {canCreateProject && (
                    <button className="btn-reset"
                      onClick={() => { setOpen(false); setCreateModalOpen(true); }}
                      style={{
                        display: 'flex', alignItems: 'center', gap: 8, width: '100%', padding: '8px 10px',
                        borderRadius: 6, color: 'var(--text-1)',
                      }}
                      onMouseEnter={(e) => e.currentTarget.style.background = 'var(--bg-2)'}
                      onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
                      <Icon name="plus" size={13} />
                      <span style={{ fontSize: 12.5 }}>Crear proyecto…</span>
                    </button>
                  )}
                  {canManageVps && (
                    <button className="btn-reset"
                      onClick={() => { setOpen(false); window.openVpsManager?.(); }}
                      style={{
                        display: 'flex', alignItems: 'center', gap: 8, width: '100%', padding: '8px 10px',
                        borderRadius: 6, color: 'var(--text-1)',
                      }}
                      onMouseEnter={(e) => e.currentTarget.style.background = 'var(--bg-2)'}
                      onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
                      <Icon name="server" size={13} />
                      <span style={{ fontSize: 12.5 }}>Gestionar VPS…</span>
                    </button>
                  )}
                </>
              )}
            </div>
          </>
        )}
      </div>
      {sideButtons}
      {createModalOpen && (
        <CreateProjectModal onClose={() => setCreateModalOpen(false)} />
      )}
      {assignVpsModalProject && (
        <AssignVpsModal
          project={assignVpsModalProject}
          onClose={() => setAssignVpsModalProject(null)}
          onAssigned={async () => {
            setAssignVpsModalProject(null);
            try { await window.loadProjects?.(); } catch {}
          }}
        />
      )}
    </div>
  );
}

// Assign / change VPS for an existing project. Shown only when the project
// row exists in DB but its `vpsId` is null. Calling PATCH /api/projects/:id
// triggers the agent to mkdir the rootDir on that VPS + write .mcp.json so
// the project is ready for Claude Code as soon as the user clicks save.
function AssignVpsModal({ project, onClose, onAssigned }) {
  const [vpsList, setVpsList] = React.useState([]);
  const [vpsId, setVpsId] = React.useState('');
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    let mounted = true;
    window.api('GET', '/api/vps').then((rows) => {
      if (!mounted) return;
      const online = rows.filter((v) => v.status === 'online' && v.agentConnected);
      setVpsList(online);
      if (online[0]) setVpsId(online[0].id);
    }).catch(() => { if (mounted) setVpsList([]); });
    return () => { mounted = false; };
  }, []);

  const submit = async (e) => {
    e.preventDefault();
    if (!vpsId || submitting) return;
    setSubmitting(true);
    setError(null);
    try {
      await window.api('PATCH', `/api/projects/${project.id}`, { vpsId });
      onAssigned && onAssigned();
    } catch (err) {
      setError(err?.body?.error || err?.message || 'No se pudo asignar el VPS.');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,.55)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 100,
    }}>
      <form onClick={(e) => e.stopPropagation()} onSubmit={submit} style={{
        width: 480, padding: 24,
        background: 'var(--bg-1)', border: '1px solid var(--border)',
        borderRadius: 'var(--r-md)', boxShadow: '0 24px 48px rgba(0,0,0,.6)',
        display: 'flex', flexDirection: 'column', gap: 14,
      }}>
        <div>
          <div style={{ fontSize: 14, fontWeight: 600 }}>Asignar VPS a "{project.name}"</div>
          <div style={{ fontSize: 12, color: 'var(--text-2)', marginTop: 4, lineHeight: 1.55 }}>
            Cuando asignes un VPS, el directorio <span className="mono">{project.rootDir}</span> se crea automáticamente en ese servidor con la configuración MCP del workspace.
          </div>
        </div>

        {vpsList.length === 0 ? (
          <div style={{
            padding: 14, fontSize: 12.5, lineHeight: 1.6,
            background: 'rgba(245,158,11,.08)', border: '1px solid rgba(245,158,11,.30)',
            borderRadius: 6, color: 'var(--text-1)',
          }}>
            No hay VPS conectados todavía. <button type="button" className="btn-reset"
              onClick={() => { onClose(); window.openVpsManager?.(); }}
              style={{ color: 'var(--accent)', textDecoration: 'underline' }}>Conecta uno primero</button>.
          </div>
        ) : (
          <Field label="VPS de destino">
            <select value={vpsId} onChange={(e) => setVpsId(e.target.value)} style={inputStyle(true)}>
              {vpsList.map((v) => (
                <option key={v.id} value={v.id}>{v.name} ({v.id} · {v.ipAddress})</option>
              ))}
            </select>
          </Field>
        )}

        {error && (
          <div style={{
            padding: '8px 12px', fontSize: 12,
            background: 'rgba(239,68,68,.10)', border: '1px solid rgba(239,68,68,.35)',
            color: 'var(--danger)', borderRadius: 6,
          }}>{error}</div>
        )}

        <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 6 }}>
          <button type="button" className="btn-reset" onClick={onClose} disabled={submitting}
            style={{ padding: '9px 14px', fontSize: 12.5, color: 'var(--text-1)' }}>Cancelar</button>
          <button type="submit" className="btn-reset" disabled={!vpsId || submitting || vpsList.length === 0}
            style={{
              padding: '9px 14px', fontSize: 12.5, fontWeight: 600,
              background: (!vpsId || submitting) ? 'var(--bg-2)' : 'var(--accent)',
              color: (!vpsId || submitting) ? 'var(--text-2)' : 'white',
              borderRadius: 'var(--r-sm)',
            }}>
            {submitting ? 'Asignando…' : 'Asignar VPS'}
          </button>
        </div>
      </form>
    </div>
  );
}

function CreateProjectModal({ onClose }) {
  const [id, setId] = React.useState('');
  const [name, setName] = React.useState('');
  const [githubRepo, setGithubRepo] = React.useState('');
  // vpsId: '' means "no VPS yet — just create the row in DB". The folder
  // gets materialised on a VPS when the user assigns one later via the
  // project switcher dropdown ("Asignar VPS…").
  const [vpsId, setVpsId] = React.useState('');
  const [vpsList, setVpsList] = React.useState([]);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    let mounted = true;
    window.api('GET', '/api/vps').then((rows) => {
      if (!mounted) return;
      // Only online VPS can receive the mkdir command. Offline ones would
      // fail at create-time, so we hide them.
      setVpsList(rows.filter((v) => v.status === 'online' && v.agentConnected));
    }).catch(() => { if (mounted) setVpsList([]); });
    return () => { mounted = false; };
  }, []);

  const slugValid = /^[a-z0-9](?:[a-z0-9-]{0,28}[a-z0-9])?$/.test(id);
  const repoValid = githubRepo === '' || /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/.test(githubRepo);
  const canSubmit = slugValid && name.trim().length > 0 && repoValid && !submitting;

  const submit = async (e) => {
    e.preventDefault();
    if (!canSubmit) return;
    setError(null);
    setSubmitting(true);
    try {
      await window.createProject({
        id, name, githubRepo: githubRepo.trim() || null,
        vpsId: vpsId || null,
      });
      onClose();
    } catch (err) {
      setError(err.body?.error || err.message || 'Error al crear el proyecto.');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,.55)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 100,
    }}>
      <form onClick={(e) => e.stopPropagation()} onSubmit={submit} style={{
        width: 460, padding: 24,
        background: 'var(--bg-1)', border: '1px solid var(--border)',
        borderRadius: 'var(--r-md)', boxShadow: '0 24px 48px rgba(0,0,0,.6)',
        display: 'flex', flexDirection: 'column', gap: 14,
      }}>
        <div>
          <div style={{ fontSize: 14, fontWeight: 600, letterSpacing: -0.2 }}>Crear proyecto</div>
          <div style={{ fontSize: 12, color: 'var(--text-2)', marginTop: 2 }}>
            Si asignas un VPS, la carpeta <span className="mono">/opt/&lt;slug&gt;</span> se crea ahí y Claude Code la usa como working dir. Puedes saltar este paso y asignar el VPS después.
          </div>
        </div>

        <Field label="Slug (id)" hint="Letras minúsculas, números y guiones. 2–30 caracteres.">
          <input value={id} onChange={(e) => setId(e.target.value)}
            placeholder="my-app" autoFocus
            className="mono"
            style={inputStyle(slugValid || id === '')} />
        </Field>

        <Field label="Nombre">
          <input value={name} onChange={(e) => setName(e.target.value)}
            placeholder="My App" style={inputStyle(true)} />
        </Field>

        <Field label="Repositorio de GitHub (opcional)" hint="owner/name. Por ahora solo guarda el metadata; no clona automáticamente.">
          <input value={githubRepo} onChange={(e) => setGithubRepo(e.target.value)}
            placeholder="usuario/repo"
            className="mono"
            style={inputStyle(repoValid)} />
        </Field>

        <Field label="VPS donde correr Claude Code" hint="Si todavía no tienes VPS, deja 'Sin asignar' y conéctalo después.">
          <select value={vpsId} onChange={(e) => setVpsId(e.target.value)}
            style={{ ...inputStyle(true), appearance: 'auto' }}>
            <option value="">Sin asignar (asignar después)</option>
            {vpsList.map((v) => (
              <option key={v.id} value={v.id}>
                {v.name} — {v.ipAddress}
              </option>
            ))}
          </select>
        </Field>

        {error && (
          <div style={{
            padding: '8px 10px', background: 'rgba(239,68,68,.08)',
            border: '1px solid rgba(239,68,68,.30)', borderRadius: 'var(--r-sm)',
            color: 'var(--text-0)', fontSize: 12.5,
          }}>{error}</div>
        )}

        <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 6 }}>
          <button type="button" className="btn-reset" onClick={onClose}
            style={{ padding: '9px 14px', fontSize: 12.5, color: 'var(--text-1)', borderRadius: 'var(--r-sm)' }}>
            Cancelar
          </button>
          <button type="submit" className="btn-reset" disabled={!canSubmit}
            style={{
              padding: '9px 14px', fontSize: 12.5, fontWeight: 600,
              background: canSubmit ? 'var(--text-0)' : 'var(--bg-2)',
              color: canSubmit ? 'var(--bg-0)' : 'var(--text-2)',
              borderRadius: 'var(--r-sm)',
              cursor: canSubmit ? 'pointer' : 'default',
            }}>
            {submitting ? 'Creando…' : 'Crear'}
          </button>
        </div>
      </form>
    </div>
  );
}

function Field({ label, hint, children }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
      <label style={{ fontSize: 11, color: 'var(--text-2)', letterSpacing: 0.4, textTransform: 'uppercase' }}>{label}</label>
      {children}
      {hint && <div style={{ fontSize: 11, color: 'var(--text-3)' }}>{hint}</div>}
    </div>
  );
}

function inputStyle(valid) {
  return {
    padding: '9px 12px',
    background: 'var(--bg-0)',
    border: `1px solid ${valid ? 'var(--border)' : 'rgba(239,68,68,.5)'}`,
    borderRadius: 'var(--r-sm)',
    color: 'var(--text-0)',
    fontSize: 13,
    outline: 'none',
  };
}

window.ProjectSwitcher = ProjectSwitcher;
window.CreateProjectModal = CreateProjectModal;
